Inheritance in JavaScript

·

2 min read

Inheritance in JavaScript

You have got some of the qualities inside you from your parents and they have got some from theirs, Inheritance is exact same concept. Inheritance allows a programmer to make a class that can have all the methods of its parent class and add even more functionalities. Got it??? Let's understand this with a short example:

// Here is a parent class
class Automobile {
    constructor(numberOfWheel) {
        this.numberOfWheel = numberOfWheel;
    }

    specification() {
        console.log(`this car has ${this.numberOfWheel} wheels.`)
    }
}

// Inherited class
class Tata extends Automobile {

}
var Maruti = new Tata(4)
Maruti.specification();

and the output of the above code is:

this car has 4 wheels.

Now suppose you want to override few properties and keep few properties same as that of parent class, you can use "super()" methods for it.

// Here is a parent class
class Automobile {
    constructor(numberOfWheel) {
        this.numberOfWheel = numberOfWheel;
        this.ownerName = "unknown";
    }
    specification() {
        console.log(`this car has ${this.numberOfWheel} wheels.`)
    }
}
// Inherited class
class Tata extends Automobile {
    constructor(numberOfWheel) {
            super(numberOfWheel);
            // override the owner's name;
            this.ownerName = "Ratan Tata"
        }
        // overriding the method of Autonobile
    specification() {
        console.log(`This car has ${this.numberOfWheel} wheels.`)
        console.log(`This car company is owned by ${this.ownerName}`)
    }
}
var Maruti = new Tata(4)
Maruti.specification();

Output of the above code section is:

This car has 4 wheels.
This car company is owned by Ratan Tata

This gives us a short idea about Inheritance but now the question is, why Inheritance? -Inheritance allows us code reusability as a child class can inherit all the methods of its parent class -You can add your own methods in child class inheriting only those methods that you want. -Code is cleaner and easier to maintain when it is structured like this.