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); };