JS class 是用來建立物件的範本,官方名稱是 class 陳述式(class declaration):用 class 關鍵字寫出一個類別,裡面放 constructor、方法、欄位等成員,再用 new 建立實例。
MDN 的說明是:JavaScript 的 class 以原型(prototype)機制為基礎,但也有 class 自己的語法與語意。常聽到的「class 是原型繼承的語法糖」只說對一半,後面「class 和函式的差異」一節會列出幾個實際不同的地方。
基本寫法
下面的 Rectangle 有一個 constructor、一個 getter 與一個一般方法:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
console.log(typeof Rectangle); // function
console.log(Object.keys(square)); // [ 'height', 'width' ]
console.log(Object.hasOwn(Rectangle.prototype, "calcArea")); // true
幾個重點:
class建出來的東西,typeof是function,MDN 稱 class 是「特殊的函式」。- 實例自己只有
constructor裡指派的屬性(height、width),方法放在Rectangle.prototype,所有實例共用。 - 類別的成員之間不用逗號隔開,這點和物件字面值不同。
使用 new 建立實例的細節,屬於 new 運算子的主題,這裡只提到它是呼叫 class 的唯一方式(下面有說明)。
宣告式與運算式
class 和函式一樣,可以寫成宣告式或運算式。運算式可以匿名,也可以自己取名字:
const Foo = class {
hi() {
return "Hello World!";
}
};
console.log(new Foo().hi(), Foo.name); // Hello World! Foo
const Bar = class NamedFoo {
who() {
return NamedFoo.name;
}
};
console.log(new Bar().who(), Bar.name); // NamedFoo NamedFoo
try {
NamedFoo.name;
} catch (e) {
console.log(e.name + ": " + e.message);
}
// ReferenceError: NamedFoo is not defined
具名的運算式,名字只在 class 本體裡看得到,要在本體裡指向自己時才需要。匿名的 class 會用接收它的變數名稱當 name。
另外,MDN 提到 class 運算式可以重新定義同一個變數,而用宣告式重複宣告同名的 class 會丟出 SyntaxError。
constructor
constructor 是建立並初始化實例的特殊方法。MDN 列出的限制有兩個:
- 一個 class 只能有一個
constructor,寫兩個會得到SyntaxError。 - 非靜態且名稱固定為
constructor的成員,不能是 getter、setter、async 或 generator。
try {
new Function("class A { constructor() {} constructor() {} }")();
} catch (e) {
console.log(e.name + ": " + e.message);
}
// SyntaxError: A class may only have one constructor
沒有自己寫 constructor 時,會有預設的:基底類別的預設 constructor 是空的;子類別的預設 constructor 會把收到的引數原封不動傳給父類別。
constructor 和一般方法一樣,可以用參數預設值、其餘參數等語法:
class P {
constructor(name = "匿名") {
this.name = name;
}
}
console.log(new P().name); // 匿名
方法、getter 與 setter
class 裡的方法可以是一般函式、async 函式、generator 函式或 async generator 函式。MDN 說明公開的實例方法定義在 prototype 上,可寫、不可列舉(non-enumerable)、可設定。
getter 與 setter 用 get、set 開頭,對外看起來像一般屬性:
class Temp {
#c = 0;
get f() {
return (this.#c * 9) / 5 + 32;
}
set f(v) {
this.#c = ((v - 32) * 5) / 9;
}
get c() {
return this.#c;
}
}
const t = new Temp();
t.f = 212;
console.log(t.c, t.f); // 100 212
console.log(Object.hasOwn(t, "f"), Object.keys(t)); // false []
MDN 說明 class 裡的 getter 定義在 prototype 上,由所有實例共用,而且不可列舉;所以上面實例本身沒有 f 這個自有屬性。
只有 getter、沒有 setter 的屬性,在嚴格模式下指派值會丟出 TypeError(MDN 的 Strict mode 頁面列為嚴格模式的錯誤之一):
try {
t.c = 5; // 範例存成 .mjs(ES 模組,預設是嚴格模式)
} catch (e) {
console.log(e.name + ": " + e.message);
}
// TypeError: Cannot set property c of #<Temp> which has only a getter
static:屬於類別本身的成員
static 定義的方法與欄位掛在類別上,不會出現在實例上。MDN 說靜態方法常用來寫工具函式,靜態欄位適合放快取或固定設定這類不需要每個實例各一份的資料。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static displayName = "Point";
static distance(a, b) {
return Math.hypot(a.x - b.x, a.y - b.y);
}
describe() {
return `${this.constructor.displayName}(${this.x}, ${this.y})`;
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log(p1.displayName, p1.distance); // undefined undefined
console.log(Point.displayName, Point.distance(p1, p2)); // Point 7.0710678118654755
console.log(p1.describe()); // Point(5, 5)
從實例方法裡要用靜態成員,MDN 的寫法有兩種:用類別名稱(Point.displayName),或透過 this.constructor(上面的 describe)。在實例上直接呼叫靜態方法(p1.distance(...))會得到 TypeError: p1.distance is not a function。
static 區塊
靜態初始化區塊(static initialization block)用 static { } 寫成,可以放多行敘述來初始化靜態成員,區塊裡的 this 是類別本身。多個區塊與靜態欄位會依宣告順序執行:
class MyClass {
static field1 = console.log("static field1");
static {
console.log("static block1");
}
static field2 = console.log("static field2");
static {
console.log("static block2");
}
}
// static field1
// static block1
// static field2
// static block2
class Config {
static values;
static {
this.values = Object.freeze({ mode: "dev" });
}
}
console.log(Config.values); // { mode: 'dev' }
區塊裡不能用 await、yield,也不能用 arguments。
公開欄位與私有欄位
在 class 本體裡直接寫 名稱 = 值,就是公開欄位(class field)。欄位是物件的屬性,不是變數,所以不寫 const、let,也不寫 public、private 這類修飾字;沒有初始值的欄位會是 undefined。
名稱前面加 # 就是私有成員,只能在 class 本體裡讀寫,MDN 說在 class 外面引用是錯誤。私有欄位、私有方法、私有 getter 與 setter、私有靜態成員都能這樣寫:
class Counter {
count = 0;
#step;
static #created = 0;
constructor(step = 1) {
this.#step = step;
Counter.#created++;
}
inc() {
this.count += this.#step;
return this;
}
#secret() {
return "私有方法";
}
reveal() {
return this.#secret();
}
static get created() {
return Counter.#created;
}
static isCounter(o) {
return #step in o;
}
}
const c = new Counter(2);
c.inc().inc();
console.log(c.count, Object.keys(c), c.reveal(), Counter.created);
// 4 [ 'count' ] 私有方法 1
console.log(Counter.isCounter(c), Counter.isCounter({}));
// true false
console.log(JSON.stringify(c)); // {"count":4}
私有成員有幾個容易忽略的規則(依 MDN 的 Private elements):
- 私有名稱必須先在 class 本體宣告,不能事後用指派建立。引用沒宣告過的
#名稱,或在 class 外面引用,都是語法錯誤(SyntaxError)。 - 不能用中括號語法存取(
c["#step"]只是一個普通字串屬性,得到undefined),也不能用delete刪除。 - 在沒有這個私有成員的物件上存取,會丟出
TypeError,不是回傳undefined。 - 想先判斷物件有沒有某個私有成員,可以用
#名稱 in 物件(上面的isCounter)。 - 私有成員不屬於原型繼承,子類別拿不到父類別的
#成員。
try {
new Function("class A { #x = 1 }; new A().#x")();
} catch (e) {
console.log(e.name + ": " + e.message);
}
// SyntaxError: Private field '#x' must be declared in an enclosing class
class C {
#x = 1;
static getX(o) {
return o.#x;
}
}
try {
C.getX({});
} catch (e) {
console.log(e.name + ": " + e.message);
}
// TypeError: Cannot read private member #x from an object whose class did not declare it
補充說明:錯誤訊息文字依引擎而不同,上面是 Node.js 22(V8)的輸出。MDN 另外提醒,Chrome 的主控台是 DevTools 專屬的放寬,可以在 class 外面讀到私有成員,不要拿來判斷程式碼在一般網頁上的行為。
私有靜態成員要用類別名稱存取
私有靜態成員只存在宣告它的那個類別上。MDN 建議用類別名稱存取,不要用 this,否則透過子類別呼叫時會失敗:
class S1 {
static #n = 42;
static viaThis() {
return this.#n;
}
static viaName() {
return S1.#n;
}
}
class S2 extends S1 {}
console.log(S2.viaName()); // 42
try {
S2.viaThis();
} catch (e) {
console.log(e.name + ": " + e.message);
}
// TypeError: Cannot read private member #n from an object whose class did not declare it
extends 與 super
extends 讓一個 class 繼承另一個建構函式(可以是 class,也可以是函式)。子類別的 constructor 要先呼叫 super(),才能使用 this;super.方法名() 可以呼叫父類別的同名方法:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
static kingdom = "Animalia";
}
class Dog extends Animal {
speak() {
return super.speak() + ` ${this.name} barks.`;
}
}
const d = new Dog("Mitzie");
console.log(d.speak()); // Mitzie makes a noise. Mitzie barks.
console.log(d instanceof Dog, d instanceof Animal); // true true
console.log(Dog.kingdom, Object.hasOwn(Dog, "kingdom")); // Animalia false
Dog 沒有自己的 constructor,所以用預設的,把引數傳給 Animal。靜態成員也會繼承:Dog.kingdom 是沿著原型鏈從 Animal 找到的,不是 Dog 自己的屬性。
MDN 說明 extends 會同時設定兩條原型鏈:
| 比較對象 | 它的原型是 |
|---|---|
Dog(類別本身) | Animal(所以靜態成員會繼承) |
Dog.prototype | Animal.prototype(所以實例方法會繼承) |
console.log(Object.getPrototypeOf(Dog) === Animal); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
取得原型的 Object.getPrototypeOf(),以及物件的 constructor 屬性,各有專文,這裡只提名稱。
子類別有 constructor 就必須呼叫 super()
在子類別的 constructor 裡,沒呼叫 super() 就用 this,會得到 ReferenceError:
class Base {
constructor(name) {
this.name = name;
}
}
class Derived2 extends Base {
constructor(name) {
this.x = 1; // 還沒呼叫 super()
super(name);
}
}
try {
new Derived2("x");
} catch (e) {
console.log(e.name + ": " + e.message);
}
// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
欄位的初始化順序
依 MDN,基底類別的欄位在 constructor 本體執行前加入;子類別的欄位則是在 super() 回傳之後才加入。所以父類別的 constructor 裡讀到子類別的欄位會是 undefined:
class Base2 {
constructor() {
console.log("Base constructor:", this.field);
}
}
class Derived extends Base2 {
field = 1;
constructor() {
super();
console.log("Derived constructor:", this.field);
}
}
new Derived();
// Base constructor: undefined
// Derived constructor: 1
extends 的限制
extends 後面必須是能用 new 呼叫、而且有 prototype 屬性的建構函式,或是 null,否則定義 class 時就會丟 TypeError:
try {
class X extends 3 {}
} catch (e) {
console.log(e.name + ": " + e.message);
}
// TypeError: Class extends value 3 is not a constructor or null
繼承內建物件(例如 Array、Error)時,MDN 提醒標準委員會認為內建物件的子類別機制設計過度,並建議考慮改用組合(composition)。
class 和函式的差異
class 以原型為基礎,但和用函式搭配 new 寫出來的「建構函式」並不完全等價。MDN 與規格明確列出的差異如下:
| 項目 | class | function 宣告 |
|---|---|---|
| 提升(hoisting) | 宣告前存取有暫時性死區(temporal dead zone,TDZ) | 整個宣告提升,可在宣告前呼叫 |
| 嚴格模式 | class 本體一律是嚴格模式 | 預設跟隨外層,沒寫 "use strict" 就不是 |
不用 new 呼叫 | 丟出 TypeError | 可以直接呼叫,行為由函式自己決定 |
不會提升可用:暫時性死區
MDN 說明 class 宣告和 let 很像:只能在宣告的位置之後存取,所以通常被視為「不會提升」。也就是說,不能像函式宣告那樣把 class 寫在檔案後面、卻在前面使用:
try {
new Late();
} catch (e) {
console.log(e.name + ": " + e.message);
}
class Late {}
// ReferenceError: Cannot access 'Late' before initialization
console.log(typeof early); // function(函式宣告可以先使用)
function early() {}
另外兩點和 let 一樣:class 宣告在腳本最上層時,不會在 globalThis 上建立屬性(函式宣告會);同一個範圍內也不能被其他宣告重複宣告(SyntaxError: Identifier 'A' has already been declared)。
內部是嚴格模式
class 本體不用寫 "use strict" 就是嚴格模式。最常見的影響,是脫離物件的方法裡 this 會是 undefined,而不是全域物件。下面用 CommonJS 腳本(本身不是嚴格模式)對照:
function Old() {}
Old.prototype.speak = function () {
return this === globalThis ? "globalThis" : String(this);
};
class New {
speak() {
return this === globalThis ? "globalThis" : String(this);
}
}
const o = new Old().speak;
const n = new New().speak;
console.log("function 方法脫離物件:", o()); // globalThis
console.log("class 方法脫離物件:", n()); // undefined
在嚴格模式下,給沒宣告過的變數賦值也會丟 ReferenceError,所以 class 方法裡寫 undeclared = 1 會報錯,而同樣的程式放在非嚴格模式的函式裡,會悄悄建立一個全域變數。
必須用 new 呼叫
class 的 constructor 永遠是建構函式,不能當一般函式呼叫。沒有 new 直接呼叫,會丟 TypeError:
class X {}
try {
X();
} catch (e) {
console.log(e.name + ": " + e.message);
}
// TypeError: Class constructor X cannot be invoked without 'new'
MDN 列出各引擎的訊息:V8 系列是 Class constructor X cannot be invoked without 'new',Firefox 是 class constructors must be invoked with 'new',Safari 是 Cannot call a class constructor without |new|。new 運算子本身另有專文,這裡只提名稱。
注意事項
- 一個 class 只有一個
constructor,重複定義是SyntaxError。 - 子類別的
constructor要先super()才能用this;沒寫constructor時用預設的即可。 - class 宣告不能在宣告前使用,要把 class 寫在使用它的程式碼之前。
- 實例方法脫離物件後
this是undefined,要當回呼函式傳出去時,記得用箭頭函式包起來,或另外綁定this。 - 私有成員用
#,不是private關鍵字;欄位也不能寫const、public。 - 私有靜態成員用類別名稱存取,不要用
this。 - React 的
class元件(class component)是用 class 寫的另一個主題,本文只提名稱,這裡不展開。
支援版本
依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24),各功能開始支援的版本如下:
class陳述式:Chrome 49、Edge 13、Firefox 45、Safari 10.1、Node.js 6.0.0、Deno 1.0、Bun 1.0.0。constructor、extends、static方法:資料與class陳述式相近,Safari 為 9,其餘同上。- 公開類別欄位:Chrome 72、Firefox 69、Safari 16、Node.js 12.0.0。
- 靜態欄位:Chrome 72、Firefox 75、Safari 14.1、Node.js 12.0.0。
- 私有欄位
#x:Chrome 74、Firefox 90、Safari 14.1、Node.js 12.0.0。 - 私有方法與存取器:Chrome 84、Firefox 90、Safari 15、Node.js 14.6.0。
#x in obj:Chrome 91、Firefox 90、Safari 15、Node.js 16.4.0。- static 初始化區塊:Chrome 94、Firefox 93、Safari 16.4、Node.js 16.11.0。
Edge 以 Chromium 為核心,上述欄位與私有成員的資料標示為沿用 Chrome 的版本。
MDN 對 class 陳述式與私有成員標示為 Baseline 廣泛可用(Widely available)。
補充說明:範例以 Node.js 22 執行,存成
.mjs(ES 模組,預設嚴格模式);「內部是嚴格模式」一節的對照範例存成.js(CommonJS)。引擎錯誤訊息依 V8 輸出。Safari 的公開欄位資料中,14 到 15.x 標示為部分支援(例如不支援公開靜態欄位、括號初始值會誤報ReferenceError),上面列的是標為完整支援的 16。
發佈留言