JS筆記:ES6 Class

基本使用

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  get x() {
    return this.x;
  }

  get y() {
    return this.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));

主意事項

  • ES6不支持private, public變量和函數,只有Typescript才有。
  • 所有的ES6 class variable都在constructor里面用this.myVarName起始。
  • 不支持function語法,寫函數直接用函數名。
  • 支持static函數,支持gettersetter,語法如上。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容