Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype inheritance, why an instance and not the prototype?

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.

like image 321
ChrisR Avatar asked Dec 06 '10 10:12

ChrisR


1 Answers

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.

like image 80
Andrzej Doyle Avatar answered Oct 16 '22 01:10

Andrzej Doyle