Facebook Pixel

What is the modern alternative to function constructors with closures in JavaScript?

ES6 classes with #private fields (ES2022). They provide true privacy without the memory cost of per-instance methods. Private fields are not accessible outside the class, and methods are shared on the prototype.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Function Constructors and Closures in JavaScript

By declaring variables with let or var inside the constructor and creating methods on this that close over them. The variables are in the constructor's local scope and are not accessible as properties, only through the methods.

Methods created inside the constructor (on this) are per-instance, not shared on the prototype. Each instance gets its own copy, which uses more memory than prototype methods. ES6 classes with #private fields solve this.

Yes. Declare a function inside the constructor (not on this). It is only accessible inside the constructor and to methods that close over it. It is not accessible as a property on instances.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.