Private members are tricky using prototypical inheritance. For one, they cannot be inherited. You need to create private members in each individual constructor. You can do this by either applying the super constructor in the subclass or create a decorator.
Decorator example:
function internalDecorator(obj){
var internal = 0;
obj.increment = function(){
return ++internal;
}
}
var A = function(){
internalDecorator(this);
}
A.prototype = {public:function(){/*etc*/}}
var B = function(){
internalDecorator(this);
}
B.prototype = new A(); // inherits 'public' but ALSO redundant private member code.
var a = new B(); // has it's own private members
var b = new B(); // has it's own private members
This is just a variation of the super constructor call, you can also achieve the same by calling the actual super constructor with .apply()
var B = function(){
A.apply(this, arguments);
}
Now by applying inheritance through B.prototype = new A()
you invoke needless constructor code from A
. A way to avoid this is to use Douglas Crockfords beget method:
Object.beget = function(obj){
var fn = function(){}
fn.prototype = obj;
return new fn(); // now only its prototype is cloned.
}
Which you use as follows:
B.prototype = Object.beget(A.prototype);
Of course, you can abandon inheritance altogether and make good use of decorators, at least where private members are needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…