Hacker News new | ask | show | jobs
by nickfargo 3626 days 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.)

2 comments

There'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.
Those wouldn't be private to each instance though, they'd be shared by all instances.
I 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.