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|
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.