Javascript - Class Inheritance and the Super Keyword

Introduction

ES6 has the extends keyword to create a child of another class.

The following code shows how to create SchoolBus by extending Bus using the extends keyword:

Demo

class Bus { 
     constructor(capacity) { //from   w w w.j a  v a 2 s . c  o  m
        this.capacity = capacity; 
     } 

     showCapacity() { 
        console.log(`Capacity of this bus: ${this.capacity}`); 
     } 
} 

class SchoolBus extends Bus { 
     load() { 
        console.log("Loading students"); 
     } 
} 

const phantom = new SchoolBus(2); 

phantom.showCapacity(); 
// Capacity of this bus: 2 

phantom.load(); 
// Loading students

Result

To define a constructor method in derived classes, use super(), which can call the parent class's constructor from the derived class.

super() is used to initialize the context, you must call super() before accessing the context (this) inside the constructor method.

If no constructor is defined, then super() is automatically called for with all the given arguments when a new instance of the class is created:

class SchoolBus extends Bus { 
        // no constructor 
        load() { 
                console.log("Loading students"); 
        } 
} 

is equivalent to

class SchoolBus extends Bus { 
        constructor(...args) { 
                super(...args); 
        } 

        load() { 
                console.log("Loading students"); 
        } 
} 

Related Topics