Inheritance and Javascript 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 OK
alert(b.array); // but b.array is containing 'hello' instead of being empty. why?

As you can see, I do not have this problem with primitive data types ... Any suggestions?

+5
source share
4 answers

Wen you write Test2.prototype = new Test(), you create a single instance Testwith a single instance of the array that is shared by each instance Test2.

Therefore, all instances Test2use the same array.

, base Test Test2, Test2.

:

function Test2() {
    Test.call(this);
}
+4

, , - :

// 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();
+3

, , , - . , OOP- Javascript.

+1

JavaScript , . JavaScript "".

( -), . , , , , .

JavaScript, , , .

, , , "". , , , , .

, , - Yahoo UI Theater. JavaScript:)

http://video.yahoo.com/watch/111585/1027823 ( )

http://developer.yahoo.com/yui/theater/ ( )

+1

All Articles