简体   繁体   中英

Javascript prototypical inheritance, comparing the ways

I ran into a blog post regarding how to interview front-end javascript developer , and confused when I saw this question.

Compare these ways of inheritance. What are the downsides?

  1. Button.prototype = new Component();
  2. Button.prototype = Component.prototype;
  3. Button.prototype = Object.create(Component.prototype);

How are these methods different from each other? Especially I have no idea between 1 and 3.

Why you should not use the first one:

var Animal = function(){
  //instance specific member food
  this.food=[];
};
Animal.prototype.eat=function(food){
  this.food.push(food);
};
var Cat = function(){};
Cat.prototype = new Animal();
var mimi=new Cat();
var maxi=new Cat();
mimi.eat("fish");
console.log(maxi.food);//=["fish"]

Creating an instance of Parent to set the prototype part of Child would cause instance specific members of Parent to be shared prototype members of Child. In sample code adding food to mimi affects food member of maxi (because both mimi and maxi get food member from Cat.prototype.food). This could be solved with Animal.call(this); in Cat constructor body (you should do that anyway to re use Animal constructor) but the food member is still present on Cat's prototype and shadowed immediately when you create an instance.

Another reason not to use this is that when creating an Animal you may need data (passed as arguments) that is not available when you define Cat and it's prototype.

Why not use the second one:

A Child is a Parent but a Parent is not a Child. In the next example a Cat and Dog is an Animal but an Animal is not a Cat (or a Dog). Setting Dog.prototype.bark will set Animal.prototype.bark which will have any child of Animal be able to bark. The Cat instance mimi can now bark.

var Animal = function(){};
var Cat = function(){};
Cat.prototype = Animal.prototype;
var Dog = function(){};
Dog.prototype = Animal.prototype;
Dog.prototype.bark=function(){
  console.log("woof woof");
};
var mimi=new Cat();
mimi.bark();//=woof woof

So you should use the third one, more on constructor functions, prototype and inheritance can be found here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM