In JavaScript, nothing is private, right? Sort of. One mechanism for creating classes with hidden member variables is to leverage Javascript’s lexical scoping. Lexical scoping means that a function’s scope is defined where it is declared, rather than where it is executed.
Here is a quick example which effectively creates a private member called “private_â€:
A question which comes to my mind is whether or not this is fast. After all, if you’re going to have an object with methods, wouldn’t using prototypes be better?
Here is an alternate implementation:
In this implementation, private_ is no longer private and can be accessed externally. However, the constructor for PrivateClass() is much simpler as the methods are assigned to the prototype once, and then reused.
So I wrote a quick benchmark to test creation of these objects and access time of these objects (these operations are fast, so I measured 20,000 iteration loops). Using Chrome 2.0, here are the results:
creation time | access time | |
via Lexical Scoping | 122.2ms | 0.18ms |
via Prototype | 11.3ms | 0.18ms |
So, if you are creating a few objects, and using them for a long time, either approach works well. But, if you are churning through many objects over time, using lexical scoping to hide private members is substantially more expensive than using prototype methods on an object.