Javascript Inheritance and Arrays
Posted
by Inespe
on Stack Overflow
See other posts from Stack Overflow
or by Inespe
Published on 2010-06-07T13:37:57Z
Indexed on
2010/06/07
13:42 UTC
Read the original article
Hit count: 153
Hi all! 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?
© Stack Overflow or respective owner