简体   繁体   English

JavaScript类继承,而不是函数

[英]Javascript class inheritance, not a function

can someone explain to me what I do wrong ? 有人可以向我解释我做错了什么吗? I want to have a base Object (class) with standard functions and with B i want to overwrite standard functionality to be more specific, so i could change class B with C and have the same functions but underlying other code. 我想拥有一个带有标准功能和B的基本对象(类),我想覆盖标准功能以更加具体,因此我可以用C更改类B并具有相同的功能,但还包含其他代码。 purpose of this all is that I need specific renderers if B or C does not have that function A should provide standard functionality. 这一切的目的是,如果B或C不具有功能A应该提供标准功能,则我需要特定的渲染器。

in C# you have function overwrite stuff but i cant seem to figure out how it works in javascript. 在C#中,您具有函数覆盖内容,但我似乎无法弄清楚它在javascript中的工作方式。

thanks in advance. 提前致谢。

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.

You're overwriting your prototype: 您正在覆盖原型:

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

That's exactly like overwriting any other variable - the latest applies. 这就像覆盖其他任何变量一样-最新适用。

And I learned this is the reliable pattern for inheritance: 我知道这是可靠的继承模式:

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"

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

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