简体   繁体   中英

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. purpose of this all is that I need specific renderers if B or C does not have that function A should provide standard functionality.

in C# you have function overwrite stuff but i cant seem to figure out how it works in 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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