Search code examples
javascriptprototype

javascript prototype inheritance overwriting methods


Here's what I have now

var Proto = function(){
    this.up = function(){ alert('hello'); };
};

Proto.prototype.up = function(){ alert('world'); };

new o = Proto();

alert(o.up); // prints "hello"

I would expect this to print "world" since I overwrite the method. Any help is appreciated.


Solution

  • See the following snippet:

    var MyClass = function () {
        this.print = function logAttachedToThis() { console.log('hello'); };
    };
    MyClass.prototype.print = function logAttachedToPrototype() { console.log('world'); };
    console.log(new MyClass());
    

    Output will be:

    MyClass {print: ƒ}
    print: ƒ printAttachedToThis()
    __proto__:
      print: ƒ printAttachedToPrototype()
      constructor: ƒ ()
      __proto__: Object
    

    When invoking new MyClass().print(), the engine will first check whether print is available in the object itself. Otherwise, it will check in the prototype chain. So actually, this.print = ... is overriding MyClass.prototype.print = .... Not sure overriding is the right word in this specific case though, I would use hiding instead.