Inheritance in Javascript - ES6

Last updated Apr 27, 2021
Inheritance is one of Object the concept in Oriented Programming. In this post we will learn how to achieve inheritance in JavaScript.Inheritance is a concept of acquire properties of one class with other class, here the clasess are called parent and child classes. This is the most important topic in object oriented programming. In this post we will learn inheritance in javascript with ES6. In ES6 Inheritance works with using the extends and super keyword.

 

Features of Inheritance

Writing reusable code in parent class and reuse in child class

 

Below example shows simple inheritance in javascript

class Mobiles {

    constructor(name, price) {
        this.name = name;
        this.price = price;
    }

    printName() {
        console.log(this.name);
    }

    printPrice() {
        console.log(this.price);
    }
}

// * Moving from Generalisation to Specialization

class TouchMobiles extends Mobiles {

    constructor(name, price, touchSensitivity) {
        super(name, price);
        this.touchSensitivity = touchSensitivity;
    }

    printTouchSensitivity() {
        console.log(this.touchSensitivity);
    }
}

    let androidP = new TouchMobiles('AndroidP', 200, 1.5);
        androidP.printName();
        androidP.printPrice();
        androidP.printTouchSensitivity();

        console.log('---------------------------------');

        let normalPhone = new Mobiles('Normal Phone', 100);
        normalPhone.printName();
        normalPhone.printPrice();

 

In the above example we created an object for the TouchMobiles() and accessed the properties of the Mobiles class and prin the details

let androidP = new TouchMobiles('AndroidP', 200, 1.5);

androidP.printName();

androidP.printPrice();

androidP.printTouchSensitivity();

 

Similarly we can directly create a parent class properties by create an object to Mobiles class

let normalPhone = new Mobiles('Normal Phone', 100);

normalPhone.printName();

normalPhone.printPrice();

 

 

Javascript inheritance example 2

class Employee {
    doWork() {
        console.log('Doing Project Work');
    }
    officeTimings() {
        console.log('office Timings are 9:00 am - 6:00 pm');
    }
    
}

class Manager extends Employee {
    salery() {
        console.log('Manager Salary is 50000');
    }
}

    let manager = new Manager();
    let employee = new Employee();
    manager.doWork();      // "Doing Project Work" 
    manager.officeTimings();      // "office Timings are 9:00 am - 6:00 pm" 
    manager.salery();      // "Manager Salary is 50000" 
      

 

Conclusion: In this example we covered how to work with inheritance in javascript with ES6 extends and super keyword.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

881 Views