我想要定义一个数组属性及其子类的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