【发布时间】:2013-01-14 12:49:37
【问题描述】:
我正在尝试以最简单的方式实现继承。我知道 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 和EfficientCar classes,对不起,函数。
【问题讨论】:
-
不认为这是最好的做法,但
return Car.prototype.getFuelConsumptionRate() / 2应该可以工作 -
@VeXii 不,浏览器说
Car.prototype.getFuelConsumptionRate不是函数。 -
这个相关问题(不是重复的)可能有用:stackoverflow.com/questions/13359363/…
标签: javascript inheritance overriding