Friday, November 15, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Super Keyword

JavaScript Super Keyword

Super keyword in JavaScript can be used to access and call on an object’s parent, it can be used in two ways.

  • As a function
  • As an object

Syntax:

super(arguments);
super.parentMethod(arguments);

Arguments: This keyword can accepts all the arguments that has been used to create a constructor.

Below example illustrates the uses of the super keyword in JavaScript.

Example:  In the constructor of the FashionDesigner class, super has been used as a function. Whereas, in the doTasks() function of the FashionDesigner class, super has been used as an object. In the constructor of the fashion designer class, the super keyword has been used as a function to call the parent class’s constructor by passing the parameters to the fashion designer. This step is important to be carried out to ensure that FashionDesigner is an instance of Person. In the doTasks() function, super is used as an object that refers to the parent class Person’s instance. Here, the super keyword is used to explicitly call the methods of the parent class Person.

Javascript




class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    atWork() {
        return this.name + " is at work, ";
    }
    atHome() {
        return this.name + " is at home";
    }
    sleeping() {
        return this.name + " is sleeping";
    }
}
class FashionDesigner extends Person {
    constructor(name, age) {
        super(name, age);
    }
    profession() {
        return this.name +
            " is a Fashion Designer";
    }
    doTasks() {
        return super.atWork() + this.profession();
    }
}
function display(content) {
    console.log(content);
}
const character =
    new FashionDesigner("Sayan", 30);
display(character.profession());
display(character.atHome());
display(character.doTasks());


Output:

Sayan is a Fashion Designer
Sayan is at home
Sayan is at work, Sayan is a Fashion Designer
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments