×
☰ See All Chapters

JavaScript ES6 Inheritance

Classes in JavaScript ES6 (like other languages) support single inheritance using extends keyword. Multiple inheritances are not supported, while a JavaScript ES6 class can have multiple subclasses, it can only have one immediate superclass. All the members of super class will be inherited into subclass (except constructor) and can be accessed directly in subclass.

If you have a constructor in your parent class then you must call the parent constructor from your sub class constructor as the first statement.

Syntax to create subclass

class SubclassName extends SuperclassName  {  

          //Members of subclass  

}

JavaScript ES6 Inheritance Example

class Box {

    length;

    width;

    height;

    constructor(length,  width,  height) {

        this.height = height;

        this.length = length;

        this.width = width;

    }

    volume()  {

      return this.length*this.width*this.height;

    }

}

 

class BoxWeight extends Box {

    length;

    width;

    height;

    depth;

    constructor(length,  width,  height, depth) {

        super(length, width, height);

        this.depth = this.depth;

    }

    volume()  {

      return super.volume()*this.depth;

    }

}

this and super

Inside a class, the instance of same class can be obtained using the “this” keyword.

Inside a class, the instance of its super class can be obtained using the “super” keyword. Also super is used to invoke superclass constructor from inside subclass constructor.

 


All Chapters
Author