我試圖以最簡單的方式實現繼承。我知道JS繼承是基於原型的,但由於我更精通OO基於類的語言,我有點偏向於將「類」邏輯封裝在「構造函數」函數中。此外,我試圖避免在原型對象中定義新成員,因爲代碼應該放在「類」功能之外。下面是我的嘗試:繼承:如何在overriden方法內模擬super.method
function Car(color, year, plate) {
this.color = color;
this.year = year;
this.plate = plate;
this.hasFuel = true;
this.fuel = 100;
this.run = function(km) {
this.fuel = this.fuel - km*this.getFuelConsumptionRate();
if(this.fuel < 0){
this.fuel = 0;
}
if(this.fuel == 0){
this.hasFuel = false;
}
};
this.getFuelConsumptionRate = function(){
return 4.2;
};
}
function EfficientCar(color, year, plate, weight){
//Emulating a super call
Car.call(this, color, year, plate);
this.weight = weight;
//Overriden method
this.getFuelConsumptionRate = function(){
return 2.2;
};
}
//Inheritance
//(I don't like this out of the method, but it is needed for the thing to work)
EfficientCar.prototype = Car;
EfficientCar.prototype.constructor = EfficientCar;
此代碼按預期工作:高效的汽車有呼籲運行在相同數量的公里後留下的更多的燃料。但是現在我想在被覆蓋的子版本中使用函數的父版本。這樣的事情:
function EfficientCar(color, year, plate, weight){
//Emulating a super call
Car.call(this, color, year, plate);
this.weight = weight;
this.getFuelConsumptionRate = function(){
return super.getFuelConsumptionRate()/2; //If only I could do this...
};
}
是否有類似於類的方式實現這種方式?我想有Car
和EfficientCar
類
,對不起,裏面的功能幾乎一切。
不認爲這是最好的初步實踐,但'返回Car.prototype.getFuelConsumptionRate()/ 2'應該工作 – VeXii
@VeXii不,瀏覽器說'Car.prototype.getFuelConsumptionRate'不是一個函數。 –
這個相關的問題(不是重複的)可能很有用:http:// stackoverflow。com/questions/13359363/javascript-when-to-define-functions-inside-constructor-and-when-to-use-prototyp –