抱歉转储问题我是 js 的新手。我想覆盖 D
“class”中的 f2()
函数。但出于某种原因,Fire Fox 告诉我:“太多的递归”。您能否指出递归发生的位置以及如何使此代码按预期工作?
var B = function () {
};
B.prototype.f2 = function (x) {
return 2 * x;
};
var C = function () {
B.call(this);
};
var D = function () {
C.call(this);
};
D.prototype.f2 = function (x) {
return C.prototype.f2.call(this, x) * 7;
};
inherit(B, C);
inherit(C, D);
function inherit(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
var d = new D();
console.log(d.f2(3));
最佳答案
两个问题:
您需要设置
XYZ.prototype
对象,在尝试向它们添加属性之前。由于您的inherit
函数会创建它们,因此您必须确保按正确的顺序执行操作。在您的
inherit
调用中,父项和子项的顺序倒置。它是inherit(child, parent)
,而不是inherit(parent, child)
。
var B = function () {
};
B.prototype.f2 = function (x) {
return 2 * x;
};
var C = function () {
B.call(this);
};
inherit(C, B); // *** Moved and updated
var D = function () {
C.call(this);
};
inherit(D, C); // *** Moved and updated
D.prototype.f2 = function (x) {
return C.prototype.f2.call(this, x) * 7;
};
function inherit(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
var d = new D();
console.log(d.f2(3));
ES2015版本,对比:
class B {
f2(x) {
return 2 * x;
}
}
class C extends B {
}
class D extends C {
f2(x) {
return super.f2(x) * 7;
}
}
const d = new D();
console.log(d.f2(3));
关于javascript - JS 继承示例 : too much recursion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40340706/