I’m trying to implement inheritance in the simplest way possible. I know JS inheritance is prototype-based, but as I’m more proficient in OO class-based languages, I’m somehow biased to keep the “class” logic encapsulated in the “constructor” function. Also I tried to avoid defining new members in the prototype object, as that code should be placed out of the “class” function. Here’s what I tried:
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;
This code works as expected: the efficient car has more fuel left after calling run for the same number of km. But now I’d like to use the parent version of a function inside the overriden child version. Something like this:
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...
};
}
Is there a way of achieving this in a class-like fashion? I’d like to have almost everything inside the Car and EfficientCar classes, sorry, functions.
If you want to call the function defined in the “superclasse”, you should use prototype properly, that is defining the functions on the prototype and not on the instance :
and the inheritance with
Then, you would be able to call the super function :
Complete demonstration (open the console)
It you make it a practice to call the super functions (a bad one in my opinion), then you can build a small method embedding and shortening the getting of the method.
If you know exactly the targeted level of inheritance, it’s easier of course, as you can simply replace
with
Note that javascript isn’t exactly the same than the other language you seem more accustomed too. Trying to apply foreign patterns leads generally to more verbose, less flexible and less maintainable programs.