1. 程式人生 > >學習筆記——super的用法

學習筆記——super的用法

code ted 實例化 去除 this end 直接 學習 ()

參考文檔:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/super

使用方法1:super就是調用一下父類的構造函數

在類繼承extends時,如果子類中存在構造函數,則必須在使用"this"之前首先調用super( ) 不然會報錯。

class myDate2 extends Date {
  constructor() {
   // 少了super,而下文中使用了this
  }

  getFormattedDate() {
    var months = [‘Jan‘,‘Feb‘,‘Mar‘,‘Apr‘,‘May‘,‘Jun‘,‘Jul‘,‘Aug‘,‘Sep‘,‘Oct‘,‘Nov‘,‘Dec‘];
    
return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear(); } } var x2 = new myDate2() // 報錯,哪怕上面去除 getFormattedDate 方法依然會報錯


使用super後不僅可以調用父類的構造函數,還可以直接通過super調用父類的方法。

使用方法2:調用父類上的靜態方法

// 先介紹一下類的靜態方法
//
1. static 關鍵字用來定義一個類的一個靜態方法。 // 2. 調用靜態方法不需要實例化該類,但不能通過一個類實例調用靜態方法。 // 3. 靜態方法通常用於為一個應用程序創建工具函數。
class Point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return Math.hypot(dx, dy); } } const p1 = new Point(5, 5); const p2 = new Point(10, 10); console.log(Point.distance(p1, p2));

舉例:

class Human {
  constructor() {}
  static ping() {
    return ‘ping‘;
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ‘ pong‘; 
  }
}
Computer.pingpong(); // ‘ping pong‘

其他註意點:

不得使用delete刪除super的屬性/方法

一個屬性定義為不可寫時,super將不能重寫這個屬性的值。

學習筆記——super的用法