4 ms·
> just use a closure! Of course, but that means allocating a closure object per method per instance. When people say they want private variables, they mean the
by nickfargo 10y ago
> just use a closure!
Of course, but that means allocating a closure object per method per instance. When people say they want private variables, they mean they want them available in regular prototype-mounted methods. Proxies are one way ES6 lets you implement that. (Another is to use a WeakMap structure alongside a constructor, where each instance created by the constructor is mapped to a separate object that holds the "private" properties of that instance. Methods close over the WeakMap, but, crucially, are defined once on the constructor's prototype.)
- iamleppert 10y agoThere's nothing preventing you from defining your private variable, method, whatever within the same scope as your prototype method. That could mean (for commonJS anyways) the same file. As long as you don't export those, they are effectively private.
- Touche 10y agoThose wouldn't be private to each instance though, they'd be shared by all instances.
- adrusi 10y agoI suppose I don't know for sure how JS runtimes implement them, but closures ought to be very cheap. They just need a reference to a static block of code and to any variables declared or referenced within. The most expensive part of using a closure is a heap allocation, and one extra allocation while creating an object in javascript is almost always negligible.