This is about “inheritance” in JavaScript.
Suppose I create a constructor Bird(), and another called Parrot() which I make to “inherit” the properties of Bird by assigning an instance of it to Parrot’s prototype, like the following code shows:
function Bird() {
this.fly = function(){};
}
function Parrot() {
this.talk = function(){ alert("praa!!"); };
}
Parrot.prototype = new Bird();
var p = new Parrot();
p.talk(); // Alerts "praa!!"
alert(p.constructor); // Alerts the Bird function!?!?!
After I’ve created an instance of Parrot, why is the .constructor property of it Bird(), and not Parrot(), which is the constructor I’ve used to create the object?
Prototype is an object just like anything else in JavaScript and object assignments are by reference. You just assigned a new bird to parrot’s prototype so parrot’s prototype is now a bird instance. And a bird’s constructor is Bird.
You could fix this with the line
Another way to do this would be to assign a clone of Bird’s prototype to Parrot.prototype
I prefer this because:
1) it saves creating an arbitrary instance of bird (what if something is counting hwo many birds have been created)
2) What if Bird constructor took an argument which was tested in the constructor body? Then
calling:
could then cause a null pointer