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.

3 answers

  • answered 2017-10-11 10:22 RogerC

    When invoking a function named "up" on an object, the JavaScript engine will look through the object for a property of type function named "up". If it doesn't find it in the object, it will look for it in the object's prototype.

    Since there is a property named "up" of type "function" in your object, it invokes this function and doesn't invoke the one defined in the prototype.

    It's working as intended.

  • answered 2017-10-11 10:28 Zaheer Ahmed

    You need to understand how prototype chain works, firstly engine finds the function in the current object i.e, Proto object, as up() is available there so it will not search in the prototype. But if it was not written in Proto object then it will search it in the prototype.

    Here is an article on prototype and inheritance written by me.

  • answered 2017-10-11 10:29 sp00m

    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.