JavaScript 在 ES6 之後才推出 class 語法,用法類似其他物件導向程式語言,都是用來建立物件。但是 JS 中的 class 本質上是基於原型(prototype)的語法糖。
如果你還不清楚原型,建議先去閱讀我的前一篇文章!【JavaScript 入門: 什麼 Prototype(原型) 和 Prototype Chain(原型鏈)】類別 (Class)
類別 (Class) 是一個用來建立物件的模板,本身也是一種函式 (Function)。類別本質上是基於原型 (Prototype) 的語法糖。
範例
class Animal{
constructor(name, sounds){
this.name = name
this.sounds = sounds
}
makeSounds(){
console.log(`I'm ${this.name}, ${this.sounds}!`);
}
}
const dog = new Animal("QQ", "Woof");
dog.makeSounds();
- 使用
class關鍵字創建類別,並將建構函式與方法寫在大括號{}中。 - 創建實例時,會自動調用
constructor()。 - class 並不是新的物件模型,而是 function
console.log(typeof Animal); // function
建構子 (Constructor)
constructor()是class的建構函式,為一個特殊方法。- 建構子名稱固定叫做 constructor。
- 每個
class都只能有一個constructor(),寫多會報錯。

- 沒有定義 constructor 的話,JS 會自動產生一個空的
constructor(){}。 - 建構函式會在實例化時自動執行,用於初始化實例的屬性 (Property)。
new
new關鍵字用來創建類別實例。- 實例化時會自動執行
constructor內的程式碼。
屬性 (Property)
類別實例的資料欄位,通常在 constructor 中設定。
方法 (Method)
定義在類別內部函式,可對屬性進行操作。方法直接寫名稱就好,不需要使用 function 關鍵字。
建構函式
與上方類別相同的作用,來回顧一下建構函式的寫法:
function Animal(name, sounds){
this.name = name
this.sounds = sounds
}
Animal.prototype.makeSounds = function(){
console.log(`I'm ${this.name}, ${this.sounds}!`);
}
const dog = new Animal("QQ", "Woof");
dog.makeSounds();
在函式內部定義屬性,方法則是寫在原型物件的 prototype 屬性。
類別與建構函式的比較
class 內的方法屬於誰
我們在 prototype 的文章說到,如果想要讓物件共用相同的方法,要手動用
Obj.prototype.method= function(){...}
把方法掛到原型物件的 prototype 屬性下,那如果是用 class 的方式,並把方法寫在 class 內部,這個方法會屬於誰? 我們可以直接用程式碼查看:
class Animal{
constructor(name, sounds){
this.name = name
this.sounds = sounds
}
makeSounds(){
console.log(`I'm ${this.name}, ${this.sounds}!`);
}
}
const dog = new Animal("QQ", "Woof");
// 新增下面這幾行
console.log(dog.hasOwnProperty('makeSounds')); // false
console.log(Object.getPrototypeOf(dog).hasOwnProperty('makeSounds')); // true
console.log(Object.getPrototypeOf(dog) === Animal.prototype); //true
- 在
dog.hasOwnProperty()這行會輸出 false,這代表這個方法並不屬於 dog 物件 Object.getPrototypeOf(dog).hasOwnProperty()這行輸出 true,代表方法在 dog 物件的原型物件上- 最後再用
Object.getPrototypeOf(dog)===Animal.prototype比對一下,結果輸出 ture,與前面手動設定的方式是一樣的。
關於 Hoisting
雖然 class 也是 function,但 class 並不會被提升(Hoisting),要宣告後才能使用。
new Animal(); // 報錯
class AnimalP{};
是否使用 new
使用類別建立物件一定要用 new 關鍵字,否則會報錯誤,使用建構函式則是允許呼叫。
總結
ES6 後推出了 class 的用法,讓 JS 與其他物件導向語言看起來更像,但實際上還是基於原型(Prototype-base)的語言。這篇文章簡單介紹了 class 的用法、 class 與 prototype 的關聯,以及 class 與 建構函式建立物件的區別。下一篇將介紹 class 的靜態方法、繼承 extends 與 super 用法。
參考
