跳到主要内容

JavaScript 类 super 关键字


实例

以下实例创建的类 "Lectcode",并使用 super 调用父类 "Site" 的构造方法 :

class Site {
constructor(name) {
this.sitename = name;
}

present() {
return '我喜欢' + this.sitename;
}
}

class Lectcode extends Site {
constructor(name, age) {
super(name);
this.age = age;
}

show() {
return this.present() + ', 它创建了 ' + this.age + ' 年。';
}
}

let lect = new Lectcode("集码教程", 5);
document.getElementById("demo").innerHTML = lect.show();

定义和用法

super 关键字用于访问和调用一个对象的父对象上的函数。。

在构造函数中使用时,super关键字将单独出现,并且必须在使用 this 关键字之前使用。super 关键字也可以用来调用父对象上的函数。

语法

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

技术细节

JavaScript 版本:ECMAScript 2015 (ES6)

浏览器支持

super 是 ECMAScript6 (ES6) 特性。

目前所有主流浏览器都支持 ES6 (JavaScript 2015) 。

ChromeEdgeFirefoxSafariOpera
YesYesYesYesYes

Internet Explorer 11 或更旧版本的 IE 不支持 super 关键字。


更多实例

在类中使用 super:

实例

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) {
// 这里,它调用父类的构造函数的,
// 作为 Polygon 的 height, width
super(length, length);

this.height; // 需要放在 super 后面,不然引发 ReferenceErro

// 注意:在派生的类中,在你可以使用'this'之前,必须先调用 super()。
// 忽略这,这将导致引用错误。
this.name = 'Square';
}
}

用 super 调用父类的静态方法:

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'