我想要定義一個數組屬性及其子類的JavaScript類。問題是,子類莫名其妙地「共享」數組屬性的所有實例:JavaScript的繼承和陣列
// 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?
正如你可以看到我沒有這個問題的基本數據類型...任何建議?
見http://stackoverflow.com/questions/1485824/javascript編程方式-inheritance-objects-declared-in-constructor-are-shared-between-inst – 2010-06-07 13:41:10