JavaScript super keyword in Class

  • by

The JavaScript super keyword is used to access and call functions on an object’s parent. This is mainly used when you have to access a variable, method, or constructor in the base class from the derived class.

super(arguments);  // calls the parent constructor (only inside the constructor)
super.parentMethod(arguments);  // calls a parent method

JavaScript super keyword

Simple example code have class named “Model” which will inherit the methods from the “Car” class, by using the extends keyword.

Gets access to the parent’s properties and methods by calling the super() method in the constructor method.

<!DOCTYPE html>
<html>
<body>
  <script>
    class Car {
      constructor(brand) {
        this.carname = brand;
      }
      present() {
        return this.carname;
      }
    }

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

    mycar = new Model("BMW", "X1");
    console.log(mycar.show());

  </script>
</body>
</html> 

Output:

JavaScript super keyword in Class

Calling super in static methods

<script>
   class Rectangle {
    constructor() {}
    static getDescription() {
      return 'Rectangle have 4 sides';
    }
  }

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

Output: Rectangle have 4 sides and are all equal

How do super() all the existing arguments?

Answer:

3

If the child and parent take the same arguments, use rest and spread:

class Child extends Parent {
  constructor(...args) {
    super(...args);
  }
}

If the constructor signatures are the same, this will work for any Child regardless of what Parent’s arguments are. This also works for multiple inherited classes, eg:

class GrandChild extends Child {
  constructor(...args) {
    super(...args);
  }
}

But long inheritance chains are usually an antipattern in JS. I’d recommend avoiding them in most cases, unless there’s a really good reason for it.

If the child has an extra trailing argument, passing it to the parent if the parent doesn’t define such an argument will work just fine.

If the child has an extra leading argument, use:

class Child extends Parent {
  constructor(childArg, ...args) {
    super(...args);
  }
}

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS super keyword.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.