JavaScript原型继承

时间:2014-09-28 02:55:22

标签: javascript

我有一些像

这样的代码
function Vehicle(){
  this.isMovable = true;
}
Vehicle.prototype = {
  hasTyres:function(){ return true;},
  needsFuel:true
};

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

现在

即使我像这样创建原型

也可以
Car.prototype = Object.create(Vehicle.prototype);

Car.prototype = Vehicle.prototype;

有什么区别?

我的印象是

Car.prototype = Object.create(Vehicle); 

会导致汽车继承车辆,但事实并非如此。

任何人都可以解释Object.create方法

中发生的事情

谢谢, SRK

2 个答案:

答案 0 :(得分:3)

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

这个创建一个原型为Vehicle.prototype的对象。在此对象中,您将Car实例的共享方法放在Vehicle的“继承”中。这是正确的方法。

Car instance -> Car prototype -> Vehicle prototype

Car.prototype = Vehicle.prototype;

此版本使用VehicleCar的相同原型。这意味着你将为这两个类破坏同一个对象。添加到Car.prototype也意味着将其添加到您不想要的Vehicle.prototype

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

Car.prototype = Object.create(Vehicle);Car.prototype是一个对象,其原型为Vehicle,一个函数。你也不想要这个。

Car instance -> Car prototype -> Vehicle function

答案 1 :(得分:1)

Vehicle是一个功能。调用Object.create(Vehicle);将创建一个对象,其原型就是该函数 那不是你想要的。

编写Car.prototype = Vehicle.prototype;将对两个类使用相同的prototype对象,因此无法仅向派生类添加函数。

有关详细信息,请参阅my blog