Inheritance

  • JS like Java does not support multiple inheritance like C++
  • Inheritance is achieved by [[Prototype]] property chain
  • Each object has only one [[Prototype]]

Inheritance using Prototype chain

Following example illustrates inheritance of Bulb from Light

function Light() {};
Light.prototype.color = 'red';
 
function Bulb() {};
Bulb.prototype = new Light();
 
Light.prototype.color = 'blue';
console.log(Bulb.color);

Inheritance using Object.create()

  • We can create another instance of object using Object.create() whose prototype points to some existing object and achieve inheritance.
function Person() {
  this.firstname = "";
  this.lastname = "Doe";
  this.greet = function () {
    console.log(this.firstname + " " + this.lastname);
  };
}
 
const person = new Person();
 
// creates a john object inheriting person object
// john prototype points to person
const john = Object.create(person);
john.firstname = "John"; // hides firstname which is inherited from person
 
const jane = Object.create(person);
jane.firstname = "Jane";
 
john.greet(); // John Doe
jane.greet(); // Jane Doe

Inheritance using ES6 classes

  • They are syntactical sugar for constructor and prototypes
  • There can only be one constructor in a class otherwise SyntaxError will happen
// Maruti.[[Prototype]] = Car
class Maruti extends Car {
    constructor() {
        // super() is used in inheritance
        // it fetches the context from the parent class
        // you must call super() so that you have access to this keyword
        super();
        // declaring and initialising fields
        this.cars = 4;
    }
    // declaring methods
    log() {
        console.log("I am logging");
    }
}