Search code examples
javascriptprototypal-inheritancemethod-invocation

Prototypal inheritance question in javascript


I understand what prototypal inheritance is all about, but I must be confused as to the implementation. I thought that modifying a function constructor's prototype would affect all instances of that constructor, but this isn't the case. How does JS do the method lookup from an object to its prototype?

Here's an example

function A(name){
  this.name = name;
}

a = new A("brad");

A.prototype = {
  talk: function(){
    return "hello " + this.name;
  }
}

a.talk() // doesn't work
b = new A("john");
b.talk() // works

I was under the impression that a would look for the method talk() in A's prototype, so any modification to A's prototype, before or after a was instantiated would be reflected, but this doesn't seem to be the case. Can someone explain this for me?


Solution

  • It's the difference between modifying and replacing the prototype.

    function A(name){
      this.name = name;
    }
    
    a = new A("brad");
    // Change, don't replace.
    A.prototype.talk = function(){
        return "hello " + this.name;
    };
    
    a.talk() // works
    b = new A("john");
    b.talk() // works
    

    Here is what is going on:

    // Continued from above
    var old_proto = A.prototype;
    
    // Nuke that proto
    A.prototype = {
    talk: function() {
        return "goodbye " + this.name;
    }
    };
    
    var c = new A("Al");
    
    a.talk() // hello brad
    b.talk() // hello john
    c.talk() // goodbye Al
    
    old_proto.say_goodbye = function() {
        return "goodbye " + this.name;
    };
    
    a.say_goodbye() // goodbye brad
    b.say_goodbye() // goodbye john
    c.say_goodbye() // TypeError c.say_goodbye is not a function.