javascript - JS 继承示例 : too much recursion

标签 javascript oop inheritance recursion overriding

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

相关文章:

oop - 给(猴子)补丁还是不给(猴子)补丁,这是个问题

java - 当我已经扩展了一个实现它的类时,我是否应该显式地实现一个接口(interface)?

C# 接口(interface)继承(基础)

python - 覆盖python中的递归方法

java多重继承ActionBarActivity

javascript - 追加行错误

javascript - 2 组按钮,但 1 组执行错误操作

javascript - IE7(及以下)的嵌套 OL 数字.数字样式列表 - Javascript 解决方案?

javascript - 何时在 Angularjs 中使用过滤器与指令

c++ - 为什么我们需要定义类的静态变量,而不是类的其他成员?