Friday, 16 June 2023

What is the super() keyword or function in JavaScript

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.


The concept of super keyword comes with the idea of inheritance in JavaScript. Suppose that you have a member variable or method of the same name in the derived class as you do in the base class.

When referring to that variable/method, how would the program know if you are referring to the base class or the derived class?


This is where super comes into play. The super keyword in JavaScript acts as a reference variable to the parent class.

It is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.

Let’s have a look at some examples to understand exactly how the super keyword works.


Example Scripts

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Class Inheritance</h2>

<p>Use the "extends" keyword to inherit all methods from another class.</p>
<p>Use the "super" method to call the parent's constructor function.</p>

<p id="demo"></p>

<script>
class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}

mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
</script>



</body>
</html>


Output :




Calling super in static methods
super can also be used to call on static methods of the parent class:

<script>
    class Rectangle {
      constructor() {}
      static getDescription() {
        return 'I have 4 sides';
      }
    }
   
    class Square extends Rectangle {
      constructor() {
        super()
      }
      static getDescription() {
        return super.getDescription() + ' which are all equal';
      }
    }
    console.log(Square.getDescription())
 </script>


The output :

I have 4 sides which are all equal




Source : https://www.w3schools.com/jsref/jsref_class_super.asp
https://www.educative.io/answers/what-is-the-super-keyword-in-javascript

No comments:

Post a Comment