开发者

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 = option开发者_高级运维s.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.


DANGER!!!

If you assign the prototype then they are the same object, any change to Cat.prototype will modify Animal.prototype

function Animal() { }
function Cat() { }
Cat.prototype = Animal.prototype;
Cat.prototype.legs = 4;
console.log(new Animal().legs + "!!"); // 4!!

Update:

By the way, to do a complete inheritance you must also inherit the constructor, calling it inside the parent:

function Animal() {
    this.onDie = new Signal();
}
function Cat() {
    Animal.call(this);
   // do your stuff here...
}
Cat.prototype = new Animal();

If not you will not get the properties the constructor injects into the instances as "onDie" on this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜