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?
It's the difference between modifying and replacing the prototype.
Here is what is going on: