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

浏览器兼容性

另见