为什么这种javascript继承会导致引用共享数组

Why does this javascript inheritance cause references to share array?

本文关键字:引用 共享 数组 javascript 继承 为什么      更新时间:2023-09-26

我有一个基类

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();

为什么我做

var S1_1 = new Sub1();
var S1_2 = new Sub1();
S1_1.Add(new Sub2());

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

这是因为原型继承就是这样工作的。所有Sub1对象都继承自一个公共Base对象。因为Base对象包含Array,所以所有Sub1实例都共享该Array。

换句话说,当你要求每个Sub1对象的.children属性时,他们会发现他们不拥有这样的属性,因此会在他们继承的原型上寻找它。由于它们继承自相同的原型对象,因此使用相同的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();

创建子时,您没有获得ownership/用this定义的基本变量的副本,您可以使用:

function Sub1(){
  Base.call(this);
}

该代码使用Sub1实例作为this上下文来调用Base。

关于原型行为的更多信息可以在这里找到:原型继承-编写