【问题标题】:Javascript class inheritance, not a functionJavascript类继承,而不是函数
【发布时间】:2015-11-18 15:37:18
【问题描述】:

有人可以向我解释我做错了什么吗? 我想有一个带有标准函数的基础对象(类),而 B 我想覆盖更具体的标准功能,所以我可以用 C 更改 B 类并具有相同的功能但底层其他代码。 这一切的目的是,如果 B 或 C 没有该功能,我需要特定的渲染器 A 应该提供标准功能。

在 C# 中你有函数覆盖的东西,但我似乎无法弄清楚它在 javascript 中是如何工作的。

提前致谢。

var A = function () {

}

A.prototype = {
    sup: function() {
        console.log("sup");
    },
    doSome: function () {
        console.log("doSomeA");
    }
}




var B = function () {
    A.call(this);

}

B.prototype = {
    doSome: function () {
        console.log("doSomeB");
    }

}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;


var a1 = new B();
a1.doSome();
a1.sup(); // Not a function.
a1.sup(); // Not a function.

【问题讨论】:

  • 除非您使用的是 IE8 - 这会导致 Object.create 出现错误 - 您的上述代码是否有效。
  • 您发布的代码确实有效;对a1.sup() 的调用不会导致错误。
  • 检查您的浏览器是否支持Object.create()

标签: javascript object inheritance prototype


【解决方案1】:

你正在覆盖你的原型:

B.prototype = { ... }
B.prototype = Object.create(A.prototype);

这与覆盖任何其他变量完全一样 - 最新版本适用。

我了解到这是可靠的继承模式:

function B() {
    // Call super constructor
    A.call(this);
}
// Clone inital properties and methods
B.prototype = Object.create(A.prototype);
// Extend the prototype
B.prototype.foo = "bar"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-25
    • 2018-08-13
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多