The story
Since assemblies may be a concept which is out of range of javascript, I don't take the internal
modifier into account, but public
, protected
and private
.
public
and private
modifiers are not that difficult to achieve; but with inheritance, protected
is significantly tricky. Yet it's not a recommended thing to do with javascript, most of articles I've read says prefix with a special character and document it.
But it seems I'm persisted to make javascript to simulate class-based languages .. I stole this idea and implemented in my way, the code is at rear of this post.
The idea behind the scene is to put higher accessibility with a higher prototype and access the highest one with a closure.
Say we have three prototypes A
, D
and G
, it looks like
As it is not possible that an object is an instance of a type also of another type which is not in the prototype chain; the way I chosen is to chain the protected
level horizontally and copy the members from the prototype of the declaring type. This makes nesting class possible, because the members declared on a less-derived type can be propagated to more-derived types; the transmit
method in my code is to do this. If A
, D
and G
have their own protected members, it would look like:
The closure for accessing the private instance, is this['']
. It takes an argument which is for identifying a class. The modifiers holder is just the class identifier, named y
in Function.extend
and _
in the test code, it should not be exposed outside the class declaration. It is also used as a shortcut of this['']
.
_['base']
is in fact not only the base constructor invoker, but also the private instances creator. It creates the private instances and updates this['']
for each constructor with the inheritance, so it should always be called in the constructors.
Although a private instance would have the access of the public members, it should not be used to alter them, since this['']
is not guaranteed to be invoked when accessing public members. But the accessing of private instance is; recent
remembers the most recently accessed private instance, and update the protected members if there're changes.
My question is, how can I get rid of this kind of refreshing the protected members? Are there better ideas to achieve the encapsulation more of the realistic?
p.s.: I actually do not want a solution which uses non-standard methods/properties .. and it would be better there're polyfills if the used methods/properties are too fashion to the old browsers.