Easy Tutorial
❮ Js Function Closures Js Void ❯

JavaScript Class super Keyword

JavaScript Class


Example

Example

The following example creates a class "tutorialpro" and uses super to call the constructor of the parent class "Site":


Definition and Usage

The super keyword is used to call functions on an object's parent.

When used in a constructor, the super keyword appears alone and must be used before the this keyword is used. The super keyword can also be used to call functions on the parent object.

Syntax

super(arguments);  // Calls the parent constructor
super.parentMethod(arguments);  // Calls the parent method

Technical Details

| JavaScript Version: | ECMAScript 2015 (ES6) |

Browser Support

super is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported by all major browsers.

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

Internet Explorer 11 or older versions do not support the super keyword.


More Examples

Using super within a class:

Example

class Polygon {
  constructor(height, width) {
    this.name = 'Rectangle';
    this.height = height;
    this.width = width;
  }
  sayName() {
    return 'Hi, I am a ', this.name + '.';
  }
  get area() {
    return this.height * this.width;
  }
  set area(value) {
    this._area = value;
  }
}

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class's constructor,
    // as the height, width of Polygon
    super(length, length);

    this.height; // Needs to be placed after super, otherwise it causes a ReferenceError

    // Note: In derived classes, `super()` must be called before you
    // can use `this`. Leaving this out will cause a reference error.
    this.name = 'Square';
  }
}

Using super to call a parent class's static method:

Example

class Rectangle {
  constructor() {}
  static logNbSides() {
    return 'I have 4 sides';
  }
}

class Square extends Rectangle {
  constructor() {}
  static logDescription() {
    return super.logNbSides() + ' which are all equal';
  }
}
Square.logDescription(); // 'I have 4 sides which are all equal'

JavaScript Class

❮ Js Function Closures Js Void ❯