class

Baseline 已廣泛支援

此特性已得到良好確立,可跨多種裝置和瀏覽器版本使用。自 2017 年 3 月起,所有瀏覽器均支援此特性。

class 宣告會建立一個新的繫結,並將其賦給指定名稱。

你也可以使用class 表示式來定義類。

試一試

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

瀏覽器相容性

另見