Javascript继承和数组

Ine*_*spe 5 javascript arrays inheritance

我试图用数组属性及其子类定义一个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?
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我对原始数据类型没有这个问题......有什么建议吗?

tbr*_*yen 1

我唯一能想到的是数组是共享引用。应该有一个明显的解决方案,因为这种经典的 OOP 代码一直都是用 Javascript 实现的。