試一試
const Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width;
}
};
console.log(new Rectangle(5, 8).area());
// Expected output: 40
語法
js
class {
// class body
}
class name {
// class body
}
描述
class 表示式與 class 宣告非常相似,且語法幾乎相同。與 class 宣告一樣,class 表示式的主體在 嚴格模式下執行。class 表示式和 class 宣告之間的主要區別是類名,class 表示式中的類名可以省略以建立匿名類。類表示式允許你重新定義類,而使用 class 宣告重新宣告一個類會丟擲 SyntaxError。有關更多資訊,請參閱 類的章節。
示例
一個基本的類表示式
這是一個匿名的類表示式,你可以使用變數 Foo 來引用它。
js
const Foo = class {
constructor() {}
bar() {
return "Hello World!";
}
};
const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"
命名類表示式
如果你想在類體內部引用當前類,你可以建立一個命名類表示式。這個名稱只在類表示式自身的範圍內可見。
js
const Foo = class NamedFoo {
constructor() {}
whoIsThere() {
return NamedFoo.name;
}
};
const bar = new Foo();
bar.whoIsThere(); // "NamedFoo"
NamedFoo.name; // ReferenceError: NamedFoo is not defined
Foo.name; // "NamedFoo"
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-class-definitions |
瀏覽器相容性
載入中…