继承的子对象在JavaScript中共享相同的数组属性

Inherited child objects share the same array property in JavaScript?

本文关键字:属性 共享 数组 JavaScript 对象 继承      更新时间:2023-09-26
> function Parent() {this.arr = [];}
undefined
> function Child() {}
undefined
> Child.prototype = new Parent();
{ arr: [] }
> child1 = new Child();
{}
> child2 = new Child();
{}
> child1.arr.push('From child1');
1
> child2.arr
[ 'From child1' ]
>

鉴于上述,我希望child2.arr是空的,因为它是自己的对象。我怎么能让孩子1和孩子2包含他们自己的arr?谢谢!

您必须在构造函数中进行赋值:

function Child() {
  this.arr = this.arr ? this.arr.slice(0) : [];
}

给每个子节点一个原型的.arr数组的副本,如果它存在的话。(这只是一个肤浅的复制,这只是一个可能的例子。)对象属性的赋值总是涉及目标对象的局部("自己的")属性,但是引用涉及原型链。

也不是说,由于相当神秘的原因,这样初始化原型不是一个好主意。最好使用Object.create:

Child.prototype = Object.create(Parent.prototype);

这将给您一个使用Parent原型对象作为其原型的新对象。

这里有一个关于这个话题的老问题,但仍然很有趣。

探讨javascript中的继承

基本上,如果属性不在对象上,你正在查看javascript查看它的原型,并试图找到它,直到它到达Object

你的Child没有属性arr,但它的原型new Parent()有,那一个是从Child1Child2引用的

function Parent() { this.arr = []; }
function Child() { this.parent = new Parent(); }
Child.prototype = new Parent();
var child1 = new Child();
var child2 = new Child();
child1.parent.arr.push('From child1');
alert(child2.parent.arr);