Skip to main content

Command Palette

Search for a command to run...

A brief guide to Super keyword in JavaScript

Published
2 min read
A brief guide to Super keyword in JavaScript
R

19, Hustler.

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

Y

"We can also use the this keyword from childCase to access the parent this object." - Nice article Rahul but i want to point something out: reason why you shouldn't use "this" to access the parent class is not because of readability, it's because it can cause infinite recursion if you have at-least 3 classes in the inheritance hierarchy: A -> B -> C.

R
Rahul5y ago

Ah. Nice explanation Yousaf

More from this blog

R

RAHULISM - FrontEnd Web Developer

232 posts

18, Hustler.