I've always wondered since i learned about prototype inheritance why you push an instance of the parent class into the child prototype and not the prototype itself?
var Animal = function(type){
this.type = type;
}
Animal.prototype.getType = function(){
return this.type;
}
var Cat = function(options){
this.breed = options.breed;
}
//Inheritance
Cat.prototype = new Animal('Cat');
Why not do the inheritance like this?
Cat.prototype = Animal.prototype;
My guess is that with only inheriting the prototype you aren't including the properties created in the constructor (this.type) but I'm not entirely sure. Anyone want to enlighten me?
But isn't putting an instance into the child class prototype putting all constructor-defined properties in the prototype too and thus introducing possible pitfalls? I'm thinking about the fact that the prototype properties are shared among all instances of a class unless they are defined in the constructor.
Well, without thinking too hard about it, if one took the latter approach then the prototype chain wouldn't actually hold. For example, let's assume that Animal
inherits from Entity
. Then Animal.prototype
would be some sort of pointer to Entity
- and then
Cat.prototype = Animal.prototype;
would set the prototype for Cat to the same prototype as Animal (i.e. some Entity reference). This would have the effect of making Cat a sibling of Animal, rather than a child as intended.
Consequently, in order to establish the prototype chain properly, an instance of the parent class must be used, so as to be able to pick up the properties of that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With