試一試
class Polygon {
constructor(height, width) {
this.area = height * width;
}
}
console.log(new Polygon(4, 3).area);
// Expected output: 12
語法
js
class name {
// class body
}
class name extends otherName {
// class body
}
描述
類宣告的類主體在嚴格模式下執行。class 宣告與let 非常相似。
class宣告的作用域是塊級和函式級。class宣告只能在其宣告位置之後才能被訪問(參見暫時性死區)。因此,class宣告通常被認為是不可提升的(與函式宣告不同)。- 當在指令碼的頂層宣告時,
class宣告不會在globalThis上建立屬性(與函式宣告不同)。 - 在同一作用域內,
class宣告不能被任何其他宣告重新宣告。
在類主體外部,class 宣告可以像 let 一樣重新賦值,但應避免這樣做。在類主體內部,繫結是常量,像 const。
js
class Foo {
static {
Foo = 1; // TypeError: Assignment to constant variable.
}
}
class Foo2 {
bar = (Foo2 = 1); // TypeError: Assignment to constant variable.
}
class Foo3 {}
Foo3 = 1;
console.log(Foo3); // 1
示例
一個類宣告
在以下示例中,我們首先定義一個名為 Rectangle 的類,然後擴充套件它以建立名為 FilledRectangle 的類。
請注意,在 constructor 中使用的 super() 只能在建構函式中使用,並且必須在可以使用 this 關鍵字之前呼叫。
js
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
}
class FilledRectangle extends Rectangle {
constructor(height, width, color) {
super(height, width);
this.name = "Filled rectangle";
this.color = color;
}
}
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-class-definitions |
瀏覽器相容性
載入中…