Skip to content Skip to sidebar Skip to footer

Javascript Inheritance With Unexpected Behaviour

I don't know how to solve the following JavaScript problem: function A() { var numbers = []; this.addNumber = function(number) { numbers.push(number); } t

Solution 1:

The problem is that when you do:

B.prototype = new A();

You set B.prototype to be an instance of A, thus B.prototype will have 2 functions that access a private variable numbers.

Now when you access (new B()).addNumber(), you will use the function from the prototype and thus the array from the prototype. All instances will use that array. All instances will push to that array.

To fix it it is enough to do:

function B() {
    A.call(this); // call superclassthis.addNumber(1);
    this.addNumber(2);
}

By calling the superclass in B's constructor, you have created a numbers variable for each instance of B, along with 2 functions which enclose over that variable. Each instance will use its specific addNumbers function which uses its specific closured array.


Since you already did that, your inheritance scheme can be simplified as well:

B.prototype = Object.create(A.prototype);

Instead of creating a new object of type A and setting that to the prototype of B, you set the prototype of B to inherit directly from the prototype of A. You still have methods defined in A's constructor because you called the superclass. The advantage is that now you no longer create instances of A for each subclass and (perhaps more important) you can now pass arguments to the constructor:

functionA(name) {
  this.name = name;
}

functionB(name) {
  A.call(this, 'B' + name);
}
B.prototype = Object.create(A.prototype);

You can't have this scenario in your inheritance model.

Solution 2:

You've got one "A" instance, and it's the prototype for the "B" constructor. Thus, each "B" instance shares that same closure variable in the "A" instance.

Post a Comment for "Javascript Inheritance With Unexpected Behaviour"