JavaScript 中的類關鍵字


在 ES6 中引入的 JavaScript 類是 JavaScript 基於原型的繼承中的語法糖。類實際上是“特殊函式”。你可以使用 class 關鍵字使用以下語法在 JavaScript 中定義類 -

class Person {
   // Constructor for this class
   constructor(name) {
      this.name = name;
   }
   // an instance method on this class
   displayName() {
      console.log(this.name)
   }
}

這本質上等效於以下宣告 -

let Person = function(name) {
   this.name = name;
}
Person.prototype.displayName = function() {
   console.log(this.name)
}

這個類也可以寫成類表示式。上述格式是類宣告。以下格式是類表示式 -

// Unnamed expression
let Person = class {
   // Constructor for this class
   constructor(name) {
      this.name = name;
   }
   // an instance method on this class
   displayName() {
      console.log(this.name)
   }
}

無論你如何按上述方式定義類,都可以使用以下方式建立這些類的物件 -

示例

let John = new Person("John");
John.displayName();

輸出

John

你可以在 https://tutorialspoint.tw/es6/es6_classes.htm 上深入瞭解 JS 類和 class 關鍵字。

更新於:2019 年 9 月 18 日

160 次檢視

開啟您的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.