本文介绍了B扩展了A,但是B.add填充了A.prototype.property的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级,另一个班级则继承了第一个班级的子级财产.

I have one class and another that inherits property children from the first one.

function A() {}
A.prototype.children = [];

function B() {}
B.prototype = new A();
B.prototype.addChild = function(Child) {
    this.children.push(Child);
};

var b = new B();
b.addChild(new Object());

奇怪的是,将b转储到控制台时,它在.children中没有任何项(如果属性.children完全存在; Chrome/Firefox),但是其原型的.children属性却被填充. 为什么?

Strangely, when dumping b to console, it has no item in .children (if property .children exists at all; Chrome/Firefox), but its prototype's .children property get populated. Why is that?

推荐答案

您的脚本中仅创建一个一个子数组,但由于以下原因,每个实例(甚至B的原型)都引用了该子数组遗产.当您按下它时,您还将从任何地方看到更改.

There is only one children array created in your script, but it is referenced by each instance (and even B's prototype) due to inheritance. When you push to it, you will see the changes from everywhere as well.

相反,给每个实例自己的数组:

Instead, give every instance its own array:

function A() {
    this.children = [];
}

而且,不要仅为使用new A 继承的所有B实例创建一个数组-而是,使用

And also, don't create only one array for all B instances to inherit from with new A - instead, use

function B() {
    A.call(this); // do everything the A constructor does on this instance
}
B.prototype = Object.create(A.prototype);
B.prototype.addChild = function(Child) {
    this.children.push(Child);
};

这篇关于B扩展了A,但是B.add填充了A.prototype.property的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:25