I am a newbie in Javascript and I just finished the long Javascript course in codeAcademy. I have some question regards prototype.
I understand that prototype is mostly used for inheritance and also to dynamically define methods to an object.
But I still have some questions. Look at my code. I defined a toString in the object Animal and also another toString, using prototype. When I run it, why it displays : [Object] Dumbo 4 and not [Proto] Dumbo 4?
function Animal(name, numLegs){
this.name = name;
this.numLegs = numLegs;
this.toString = function(){
return "[Object]" + this.name + " " + this.numLegs + "\n";
};
}
Animal.prototype.toString = function(){
return "[Proto]" + this.name + " " + this.numLegs + "\n";
};
var animal = new Animal("Dumbo", 4);
console.log(animal.toString());
toStringin runtime every time you create an object. Putconsole.logwith some message beforeAnimal.prototype.toStringand another beforethis.toString[[Prototype]]chain. So the one on the instance (assigned in the constructor, so each instance has its own copy) is found before the inherited one (which each instance shares).thisin JavaScript: stackoverflow.com/a/19068438/1641941