I think I have misunderstood how Javascript prototypal inheritance works. Specifically, the prototypes internal variables seem to be shared between multiple different sub-objects. It is easiest to illustrate with code:
var A = function()
{
var internal = 0;
this.increment = function()
{
return ++internal;
};
};
var B = function() {};
// inherit from A
B.prototype = new A;
x = new B;
y = new B;
$('#hello').text(x.increment() + " - " + y.increment());
This outputs 1 - 2 (test it on JSBin), while I fully expected the result to be 1 - 1, since I wanted two separate objects.
How can I make sure that the A object isn’t shared object between multiple instances of B?
Update: This article highlights some of the issues:
The problem is that the scope each approach uses to create a private variable, which works fine, is also the closure, in action, that results in if you change a private variable for one object instance, it is being changed for all. I.e. it’s more like a private static property, than an actual private variable.
So, if you want to have something private, more like a non-public constant, any of the above approaches is good, but not for actual private variables. Private variables only work really well with singleton objects in JavaScript.
Solution: As per BGerrissen’s answer, changing the declaration of B and leaving of the prototype works as intended:
var B = function() { A.apply(this, arguments); };
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:
This is just a variation of the super constructor call, you can also achieve the same by calling the actual super constructor with
.apply()Now by applying inheritance through
B.prototype = new A()you invoke needless constructor code fromA. A way to avoid this is to use Douglas Crockfords beget method:Which you use as follows:
Of course, you can abandon inheritance altogether and make good use of decorators, at least where private members are needed.