简体   繁体   English

JS继承示例:过多的递归

[英]JS Inheritance example: too much recursion

Sorry for dump question I am new to js. 对不起,转储问题我是JS新手。 I would like to override f2() function in D "class". 我想在D “类”中覆盖f2()函数。 But for some reason Fire Fox told me: "too much recursion". 但是出于某种原因,Fire Fox告诉我:“递归太多”。 Could you please point me where recursion happening and how to make this code work as expected? 您能否指出我递归发生的位置以及如何使此代码按预期工作?

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));

Two problems: 两个问题:

  1. You need to set up the XYZ.prototype objects before you try to add properties to them. 尝试向其添加属性之前,需要设置XYZ.prototype对象。 Since your inherit function creates them, you must ensure that you do things in the right order. 由于inherit函数会创建它们,因此您必须确保以正确的顺序执行操作。

  2. You have the order of the parent and child backward in your inherit calls. inherit调用中,父级和子级的顺序向后。 It's inherit(child, parent) , not inherit(parent, child) . 它是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)); 

The ES2015 version, for comparison: 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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM