> 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
它是空的,因为它是它自己的对象。我如何让child1和child2包含自己的arr?谢谢!
您必须在构造函数中进行赋值:
function Child() {
this.arr = this.arr ? this.arr.slice(0) : [];
}
.arr
如果存在,这将为每个孩子提供原型数组的副本。(这只是一个浅表副本,这只是一个可能的示例。)对对象属性的分配始终涉及目标对象的本地(“自己的”)属性,而引用涉及原型链。
同样也不是出于相当不可思议的原因,初始化这样的原型并不是一个好主意。更好地使用Object.create
:
Child.prototype = Object.create(Parent.prototype);
这为您提供了一个将Parent
原型对象用作其原型的新对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句