super關鍵字用於訪問和調用一個對象的父對象上的函數。super.prop和super[expr]表達式在類和對象字面量任何方法定義中都是有效的。
語法
super([arguments]);
// 調用 父對象/父類 的構造函數
super.functionOnParent([arguments]);
// 調用 父對象/父類 上的方法
在構造函數中使用時,super關鍵字將單獨出現,而且必須在使用this關鍵字以前使用。
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
}
class Square extends Polygon {
constructor(length) {
this.height;
// ReferenceError,super 須要先被調用!
/*
這裏,它調用父類的構造函數的 length,
做爲Polygon 的 width和 height.
*/
super(length, length);
/*
注意: 在派生的類中, 在你可使用'this'以前, 必須先調用super()。
忽略這, 這將致使引用錯誤。
*/
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
https://developer.mozilla.org...函數