我正在尝试定义一个带有数组属性的 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?
如您所见,原始数据类型没有这个问题...有什么建议吗?
最佳答案
当您编写 Test2.prototype = new Test()
时,您创建了一个单独的 Test
实例,其中包含一个数组实例,该实例由每个 共享Test2
实例。
因此,所有 Test2
实例都共享同一个数组。
您可以通过从 Test2
构造函数调用基础 Test
构造函数来解决这个问题,这将为每个 Test2
创建一个新的数组实例实例。
例如:
function Test2() {
Test.call(this);
}
关于Javascript 继承和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2989966/