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?
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);
}
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With