简体   繁体   English

JavaScript原型继承

[英]JavaScript Prototypical Inheritance

I've some code like 我有一些像

function Vehicle(){
  this.isMovable = true;
}
Vehicle.prototype = {
  hasTyres:function(){ return true;},
  needsFuel:true
};

var Car  = function(){
  Vehicle.call(this);
  this.type = "Car";
};

Now 现在

It works even if I create prototype like this 即使我创建这样的原型也可以

Car.prototype = Object.create(Vehicle.prototype);

or 要么

Car.prototype = Vehicle.prototype;

What is the difference ? 有什么区别 ?

I was under the impression that 我的印象是

Car.prototype = Object.create(Vehicle); 

will cause Car to inherit from vehicle ,but it's not. 会导致Car从车辆继承,但事实并非如此。

Can anyone explain what's happening inside Object.create method 任何人都可以解释Object.create方法内部发生的情况

Thanks, SRK 谢谢,SRK

Car.prototype = Object.create(Vehicle.prototype);

This one creates an object whose prototype is Vehicle.prototype . 这将创建一个对象,其原型为Vehicle.prototype In this object, you put your shared methods for Car instances while "inheriting" from Vehicle . 在这个对象,你把你的共享方法Car情况下,同时从“继承” Vehicle This is the right way to go. 这是正确的方法。

Car instance -> Car prototype -> Vehicle prototype

Car.prototype = Vehicle.prototype;

This one uses the same prototype for Vehicle to Car . 这其中使用了相同的原型VehicleCar This means that you'll be clobbering the same object for both classes. 这意味着您将破坏两个类的相同对象。 Adding to Car.prototype would mean also adding it to Vehicle.prototype , which you don't want. 添加到Car.prototype意味着将它也添加到Vehicle.prototype ,这是您不想要的。

Car instance -> Car prototype (which is also Vehicle prototype)

Car.prototype = Object.create(Vehicle); , Car.prototype is an object whose prototype is Vehicle , a function. Car.prototype是一个对象,其原型是Vehicle ,一个函数。 You don't want this either. 你也不想要这个。

Car instance -> Car prototype -> Vehicle function

Vehicle is a function. Vehicle是一种功能。 Calling Object.create(Vehicle); 调用Object.create(Vehicle); will create an object whose prototype is that function. 将创建其原型为该功能的对象。
That's not what you want. 那不是你想要的。

Writing Car.prototype = Vehicle.prototype; 编写Car.prototype = Vehicle.prototype; will use the same prototype object for both classes, making it impossible to add a function to the derived class only. 将为两个类使用相同的prototype对象,从而无法仅将函数添加到派生类。

For more details, see my blog . 有关更多详细信息,请参见我的博客

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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