Zezura
Zezura

Reputation: 126

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.

Upvotes: -1

Views: 772

Answers (1)

Tomáš Zato
Tomáš Zato

Reputation: 53129

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"

Upvotes: 4

Related Questions