Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Inheritance and Arrays

I am trying to define a javascript class with an array property, and its subclass. The problem is that all instances of the subclass somehow "share" the array property:

// class Test
function Test() {
    this.array = [];
    this.number = 0;
} 

Test.prototype.push = function() {
   this.array.push('hello');
   this.number = 100;
}

// class Test2 : Test
function Test2() {
}

Test2.prototype = new Test();

var a = new Test2();
a.push(); // push 'hello' into a.array

var b = new Test2();
alert(b.number); // b.number is 0 - that's OK
alert(b.array); // but b.array is containing 'hello' instead of being empty. why?

As you can see I don't have this problem with primitive data types... Any suggestions?

like image 902
Inespe Avatar asked Jun 07 '10 13:06

Inespe


3 Answers

Wen you write Test2.prototype = new Test(), you create a single Test instance, with a single array instance, which is shared by every Test2 instance.

Therefore, all of the Test2 instances are sharing the same array.

You can solve this problem by calling the base Test constructor from the Test2 constructor, which will create a new array instance for every Test2 instance.

For example:

function Test2() {
    Test.call(this);
}
like image 113
SLaks Avatar answered Oct 21 '22 13:10

SLaks


Another, rather inelegant, alternative is to move initialization code from the constructor to a method and call it from both constructors:

// class Test
function Test() {
  this.init();
} 

Test.prototype.init = function() {
    this.array = [];
    this.number = 0;
};

Test.prototype.push = function() {
   this.array.push('hello');
   this.number = 100;
};

// class Test2 : Test
function Test2() {
  this.init();
}

Test2.prototype = new Test();
like image 34
Tim Down Avatar answered Oct 21 '22 13:10

Tim Down


Only thing I can think of is that arrays are shared references. There should be an obvious solution since this kind of classic OOP code is implemented all the time in Javascript.

like image 41
tbranyen Avatar answered Oct 21 '22 11:10

tbranyen