A brief guide to Super keyword in JavaScript

A brief guide to Super keyword in JavaScript

·

2 min read

The super keyword is used to access or call functions of the object's parent. super.prop can be used to access parent class properties.

Syntax:

// way to use
super(); // calls the parent constructor

super.functionOnParent(); // calls parent function

super.parentProp; // to access parent property

EXAMPLE-

class ParentClass {
    constructor() {
        console.log('parent class');

        // this keyword is used to refer the current class
        this.parentVariable = 'parent variable';
    }
    parentMethod() {
        console.log('parent method'); 
    }
};

We have created a ParentClass, let's inherit and use the super keyword.

class ChildClass extends ParentClass {
    constructor() {
        console.log('child class'); 
        super(); // calls the parent constructor
    }
    childMethod() {
        console.log(super.parentVariable); 
    }
}; 

var childClass = new ChildClass(); 
// => child class
// => parent class

childClass.childMethod(); 
// => child method
// => parent method
// => parent variable

Super vs This keyword

We can also use the this keyword from childCase to access the parent this object. But the super keyword will avoid confusions of readability.

Let's see an example...

class ChildClass extends ParentClass {
    childMethod() {
        super.parentMethod(); 
        this.parentMethod(); 
    }
}; 

var childClass = new ChildClass(); 

childClass.childMethod(); 
// => parent method
// => parent method

Removal.AI - [SPONSOR]

Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.

  • ✅ Drag & Drop Multiple Images
  • ✅ Optimize Product Images
  • ✅ Select Your Background
  • ✅ Set Your Output Size
  • ✅ Exceptional Results

Removal AI

Visit -> Removal AI

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!