2014-09-28 139 views
1

我已經喜歡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

如果你想知道什麼'Object.create'呢,看看在MDN文檔:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create – 2014-09-28 03:00:28

+0

汽車是一輛汽車,但汽車不一定是汽車(可以是公交車)。所以你不能將它們的原型設置爲彼此相等。更多關於這裏的原型。 http://stackoverflow.com/a/16063711/1641941 – HMR 2014-09-28 03:30:16

回答

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

Vehicle是一個函數。調用Object.create(Vehicle);將創建一個原型爲該函數的對象。
這不是你想要的。

寫入Car.prototype = Vehicle.prototype;將爲這兩個類使用相同的prototype對象,從而無法將函數僅添加到派生類。

有關更多詳細信息,請參閱my blog