I am trying to get my head around Object Oriented Programming in Javascript and bumped into the following issue: (This is a simplified example of what can be found in Stoyan Stefanov’s book)
I create a constructor function to create Dog objects:
function Dog(){
this.tail = true;
}
Then I instantiate an object using Dog constructor function:
var benji = new Dog();
Then I assign a new property to Dog’s prototype object:
Dog.prototype.shout = 'Woof!';
Now, benji has access to both tail, as well as shout, as expected. All is well until I overwrite Dog’s prototype:
Dog.prototype = {paw : 4};
Now, benji.paw becomes undefined. My question is, shouldn’t benji have access to the new prototype object as well? What’s more baffling is, when I create a new instance of Dog after the prototype object was re-defined:
var lucy = new Dog();
lucy.paw evaluates to 4. lucy’s constructor object definition seems to be different from benji’s. I am quite confused what’s going on here, can someone explain how javascript’s memory model for objects work? Thanks.
prototypeis just an object.If you do
var oldProto = Dog.prototypebefore you overwrite it
Dog.prototype = { paws: 4 }then you can use the old prototype object for manipulations of its children:
oldProto.teeth = true—>benji.teeth == true.