gpt4 book ai didi

javascript - JS 继承示例 : too much recursion

转载 作者:行者123 更新时间:2023-11-30 08:29:17 25 4
gpt4 key购买 nike

抱歉转储问题我是 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));

最佳答案

两个问题:

  1. 您需要设置 XYZ.prototype 对象,尝试向它们添加属性之前。由于您的 inherit 函数会创建它们,因此您必须确保按正确的顺序执行操作。

  2. 在您的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com