我有一些像
这样的代码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
答案 0 :(得分:3)
Car.prototype = Object.create(Vehicle.prototype);
这个创建一个原型为Vehicle.prototype
的对象。在此对象中,您将Car
实例的共享方法放在Vehicle
的“继承”中。这是正确的方法。
Car instance -> Car prototype -> Vehicle prototype
Car.prototype = Vehicle.prototype;
此版本使用Vehicle
到Car
的相同原型。这意味着你将为这两个类破坏同一个对象。添加到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。