此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
super
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年3月.
super 關鍵字被使用於通過函式存取父層
super.prop 與super[expr] 表達有效在method definition 與classes 與object literals.
In this article
語法
super([arguments]); // calls the parent constructor.super.functionOnParent([arguments]);
描述
當使用建構子,super 關鍵字必須出現在this 關鍵字之前使用,super 關鍵字也可以使用在呼叫函式與父對象
範例
>在類別中使用super
這個程式碼片段從classes sample (live demo). 這裏的super() 被呼叫去避免複製到建構子的Rectangle 與Square 的共通部分。
js
class Rectangle { constructor(height, width) { this.name = "Rectangle"; this.height = height; this.width = width; } sayName() { console.log("Hi, I am a ", this.name + "."); } get area() { return this.height * this.width; } set area(value) { this.area = value; }}class Square extends Rectangle { constructor(length) { this.height; // ReferenceError, super needs to be called first! // Here, it calls the parent class's constructor with lengths // provided for the Rectangle's width and height super(length, length); // Note: In derived classes, super() must be called before you // can use 'this'. Leaving this out will cause a reference error. this.name = "Square"; }}Super-calling 靜態方法
你也可以使用在靜態方法.
js
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'刪除 super 屬性將拋出錯誤
你不能使用delete operator 以及super.prop 以及super[expr] 去刪除父層的類別屬性, 不然他會丟出一個錯誤ReferenceError.
js
class Base { constructor() {} foo() {}}class Derived extends Base { constructor() {} delete() { delete super.foo; // this is bad }}new Derived().delete(); // ReferenceError: invalid delete involving 'super'.super.prop 不能複寫在不能複寫的屬性
當定義不可寫屬性,例如Object.defineProperty,super 不能複寫這個屬性的值.
js
class X { constructor() { Object.defineProperty(this, "prop", { configurable: true, writable: false, value: 1, }); }}class Y extends X { constructor() { super(); } foo() { super.prop = 2; // Cannot overwrite the value. }}var y = new Y();y.foo(); // TypeError: "prop" is read-onlyconsole.log(y.prop); // 1使用super.prop 在對象符號
Super 可以使用在object initializer / literal 符號. 在這個範例, 有兩個對象定義在一個方法. 在第二個對象裡面,super 呼叫了第一個對象的方法. 這個動作幫助Object.setPrototypeOf() 讓我們可以設定原型obj2 toobj1, 所以super 可以發現method1 在obj1裡被找到.
js
var obj1 = { method1() { console.log("method 1"); },};var obj2 = { method2() { super.method1(); },};Object.setPrototypeOf(obj2, obj1);obj2.method2(); // logs "method 1"規格
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-super-keyword> |