Mister Smith
Mister Smith

Reputation: 28168

Inheritance: How to emulate super.method inside overriden method

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.

Upvotes: 1

Views: 149

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

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 :

Car.prototype.getFuelConsumptionRate = function() {
 return 4.2; 
}

and the inheritance with

EfficientCar.prototype = new Car();

Then, you would be able to call the super function :

EfficientCar.prototype.getFuelConsumptionRate = function(){
   var superfun = this.constructor.prototype.constructor.prototype.getFuelConsumptionRate;
   return superfun.call(this) / 2;
};  

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

var superfun = this.constructor.prototype.constructor.prototype.getFuelConsumptionRate;

with

var superfun = EfficientCar.prototype.getFuelConsumptionRate;

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.

Upvotes: 1

Rik
Rik

Reputation: 3596

I do it like this, using a shim for Object.create() when it's not supported.

var Car = function() {
    // code
};

Car.prototype.getFuelConsumptionRate = function() {
    // code
};


var EfficientCar = function() {
    Car.call(this);
};

EfficientCar.prototype = Object.create(Car.prototype);

EfficientCar.prototype.getFuelConsumptionRate = function() {
    var result = Car.prototype.getFuelConsumptionRate.call(this)
    // code
};

Upvotes: 0

Jakub Konecki
Jakub Konecki

Reputation: 46008

If you want to use inheritance in javascript I would suggest you use this little gem from John Resig:

http://ejohn.org/blog/simple-javascript-inheritance/

Example from the blog:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },
  dance: function(){
    return this.dancing;
  }
});

var Ninja = Person.extend({
  init: function(){
    this._super( false );
  },
  dance: function(){
    // Call the inherited version of dance()
    return this._super();
  },
  swingSword: function(){
    return true;
  }
});

var p = new Person(true);
p.dance(); // => true

var n = new Ninja();
n.dance(); // => false
n.swingSword(); // => true

// Should all be true
p instanceof Person && p instanceof Class &&
n instanceof Ninja && n instanceof Person && n instanceof Class

Upvotes: 2

Related Questions