Rud*_*koŭ 1 javascript oop recursion inheritance overriding
抱歉转储问题我是js的新手.我想覆盖"类"中的f2()
函数D
.但由于某些原因,火狐告诉我:"过多的递归".你能否指出我递归发生的地方以及如何使这段代码按预期工作?
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));
Run Code Online (Sandbox Code Playgroud)
两个问题:
在尝试向其添加属性之前,需要设置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));
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)