JavaScript 類(class) super 關鍵字
實例
實例
以下實例創建的類 "Runoob",並使用 super 調用父類 "Site" 的構造方法 :
class Site {
constructor(name) {
this.sitename = name;
}
present() {
return '我喜歡' + this.sitename;
}
}
class Runoob extends Site {
constructor(name, age) {
super(name);
this.age = age;
}
show() {
return this.present() + ', 它創建了 ' + this.age + ' 年。';
}
}
let noob = new Runoob("菜鳥教程", 5);
document.getElementById("demo").innerHTML = noob.show();
嚐試一下 »
定義和用法
super 關鍵字用於訪問和調用一個對象的父對象上的函數。。
在構造函數中使用時,super關鍵字將單獨出現,並且必須在使用 this 關鍵字之前使用。super 關鍵字也可以用來調用父對象上的函數。
語法
super(arguments); // 調用父構造函數 super.parentMethod(arguments); // 調用父方法
技術細節
JavaScript 版本: | ECMAScript 2015 (ES6) |
瀏覽器支持
super 是 ECMAScript6 (ES6) 特性。
ES6 (JavaScript 2015) 支持目前所有主流的瀏覽器。
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
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'
嚐試一下 »
點我分享筆記