我正在尝试以最简单的方式实现继承。我知道 JS 继承是基于原型的,但由于我更精通基于 OO 类的语言,我有点偏向于将“类”逻辑封装在“构造函数”函数中。我还试图避免在原型对象中定义新成员,因为该代码应该放在“类”函数之外。这是我尝试过的:
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
and EfficientCar
classes中,对不起,函数。