In JavaScript it is not possible to create properties that have limited or controlled accessibility. It is possible to create non-enumerable and non-writable properties, but still they can be discovered and accessed. Usually so called “closure capturing” pattern is used to encapsulate such properties in lexical scope:
Unfortunately given approach does not works very well with OO inheritance:
- Code readability degrades and some code duplication becomes necessary.
(See firs lines ofBase
andDecedent
constructors). - Prototypes do not contain any properties and there for each instance gets
it’s own fresh copy of them.
(Not very good for performance). - Own and inherited methods access different copies of private properties and
there for changes do not propagate.
_(boom
method ofDecedent
illustrates the issue). - Access to a private properties can not be shared with a limited group.
I believe because of these reasons “-
” prefix was established as a “de facto”
standard for private property names. Unfortunately it’s just a coding style that
does not implies any property access restrictions.
In Jetpack we’ve explored different techniques to overcome issues mentioned above, but property access sharing to the limited groups of consumers remained painful and unobvious.
Recently I got an interesting idea inspired by private names proposal for ECMAScript (I recommend to reading Allen Wirfs blog post explaining details of the proposal). Here is an illustration of the idea with a same example:
Please note that this solves all the issues outlined. Also access to the
privates can be shared with any group, just by giving them a KEY
. After
tinkering with this idea for some time, I’m happy to announce birth of
namespace micro-library. Below you can see same example, but this time coded
as a commonjs module and using mentioned library:
Library not only wraps outlined idea into a nice API, but also allows provides a way to use multiple namespaces with the same object.
Finally here is a jsfiddle link containing this example if you wan to play with it. Of course comments / feedback / ideas is more then welcome!