为什么这个javascript继承导致共享数组的引用?

Win*_*ker 2 javascript oop prototype

我有一个基类

function Base(){
    this.children = new Array();
}
Base.prototype.Add = function(child){
    this.children.push(child)
}

function Sub1(){...}
Sub1.prototype = new Base();

function Sub2(){...}
Sub2.prototype = new Base();
Run Code Online (Sandbox Code Playgroud)

那我该怎么办呢

var S1_1 = new Sub1();
var S1_2 = new Sub1();
S1_1.Add(new Sub2());
Run Code Online (Sandbox Code Playgroud)

S1_2由于某种原因也有1个孩子并且包含与我添加到S1_1的孩子相同的信息?

小智 6

这是因为原型继承的工作原理.所有Sub1对象都从公共Base对象继承.由于该Base对象包含Array,因此所有Sub1实例都共享该Array.

换句话说,当你要求.children每个Sub1对象的属性时,他们会看到他们没有这样的属性,因此会在他们继承的原型上查找它.由于它们继承自相同的原型对象,因此它们使用相同的Array.


要使每个Sub1都有自己的Array,您应该在Sub1构造函数中定义它.

function Base(){
    this.children = new Array();
}
Base.prototype.Add = function(child){
    this.children.push(child); // `this` will be whatever object invoked the method
}

function Sub1(){
    this.children = [];
}
Sub1.prototype = new Base();

function Sub2(){
    this.children = [];
}
Sub2.prototype = new Base();
Run Code Online (Sandbox Code Playgroud)