freakinpenguin
freakinpenguin

Reputation: 867

Javascript override prototypes method

Maybe someone can explain to me, why I can't override the method moep from B's prototype-class. I've found an example (http://stackoverflow.com/questions/11148960/javascript-prototype-method-override-not-found) and if I'm overriding the function with B.prototype = ... it works. So why do I have to specify the .prototype to override the function?

Greetings - Thomas

A = function() {
    this.moep = function() { 
        alert("Im in class A!");  
    };
};

B = function() {
};

B.prototype = new A();
B.moep = function() { 
    alert("Im outside!");  
};

var keks = new B();
keks.moep(); // Alerts "Im in class A"

Upvotes: 0

Views: 4754

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

You're assigning to B.moep, not B.prototype.moep or (within B) this.moep. B.moep isn't involved in the prototype chain at all.

When you create objects via new <functionname>, the object's prototype is set from <functionname>.prototype. So if you want to override the moep assigned by A to the instance created by new A and assigned to B.prototype, you need to assign to B.prototype.

Upvotes: 3

Related Questions