淺談ES6中super關鍵字


作用:

super 關鍵字用於訪問父對象上的函數。

語法:

super([arguments]); // 訪問父對象上的構造函數
super.functionOnParent([arguments]); // 訪問對象上的方法

詳解:

super可以用在類的繼承中,或者對象字面量中,super指代了整個prototype或者__proto__指向的對象

1 類(prototype相關)

a 用在子類constructor函數中

 1 class Person {
 2   constructor (name) {
 3     this.name = name;
 4   }
 5 }
 6 class Student extends Person {
 7   constructor (name, age) {
 8     super(); // 用在構造函數中,必須在使用this之前調用
 9     this.age = age;
10   }
11 }

super()調用會生成一個空對象,作為context來調用父類的constructor,返回this對象,作為子類constructor的context繼續調用構造函數。

context:執行上下文 constructor:構造函數

b 調用父類的靜態函數

 1 class Human {
 2   constructor() {}
 3   static ping() {
 4     return 'ping';
 5   }
 6 }
 7 
 8 class Computer extends Human {
 9   constructor() {}
10   static pingpong() {
11     return super.ping() + ' pong';
12   } // 只有在子類的靜態函數中才能調用父類的靜態函數(babel環境測試,按理說,在實例函數中應該也可以調用,不過實際測試環境中報錯)
13 }
14 Computer.pingpong(); // 'ping pong'

2 對象的字面量(__proto__項目)

 1 var obj1 = {
 2   method1() {
 3     console.log("method 1");
 4   }
 5 }
 6 
 7 var obj2 = {
 8   method2() {
 9    super.method1();
10   }
11 }
12 // 必須利用setPrototypeOf將第二個對象的原型設為第一個對象
13 Object.setPrototypeOf(obj2, obj1);
14 obj2.method2(); // logs "method 1"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM