-1

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.
3
  • Unless you are on IE8 - which would result in an error with Object.create - will your above code work. Commented Nov 18, 2015 at 15:40
  • 1
    The code you posted actually works; the calls to a1.sup() do not result in errors. Commented Nov 18, 2015 at 15:40
  • 1
    check if your browser supports Object.create() Commented Nov 18, 2015 at 15:43

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.