JavaScript Classes (class)superKeyword

JavaScript 类(class)JavaScript Classes (class)


Example

Example

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

class Site { constructor(name) { this.sitename = name; } present() { return 'I like' + this.sitename; } } class Example extends Site { constructor(name, age) { super(name); this.age = age; } show() { return this.present() + ', it was founded' + this.age + 'years.'; } } let noob = new Example("Example", 5); document.getElementById("demo").innerHTML = noob.show();

Try it Yourself »


Definition and Usage

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

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

Syntax

super(arguments);  // 调用父构造函数
  super.parentMethod(arguments);  // 调用父方法
  

Technical Details

JavaScript Version: ECMAScript 2015 (ES6)

Browser Support

super is an ECMAScript6 (ES6) feature.

Currently all major browsers support ES6 (JavaScript 2015).

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

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


More Examples

Using super in 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 constructor of the parent class, //as Polygon's height, width super(length, length); this.height; //need to be placed after super, otherwise a ReferenceError is caused. //Note: In a derived class, you must call super() before you can use 'this'. //Ignoring this will cause a reference error. this.name = 'Square'; } }

Try it Yourself »

Calling the parent class's static method with super:

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'

Try it Yourself »

JavaScript 类(class)JavaScript Classes (class)

Other Extensions