class

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2016.

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 name extends otherName {
  // 类体
}

描述

类声明的类体在严格模式下执行。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 的类。

请注意,super() 只能在 constructor 中使用,并且必须在使用 this 关键字之前调用。

js
class Rectangle {
  constructor(height, width) {
    this.name = "矩形";
    this.height = height;
    this.width = width;
  }
}

class FilledRectangle extends Rectangle {
  constructor(height, width, color) {
    super(height, width);
    this.name = "填充矩形";
    this.color = color;
  }
}

规范

Specification
ECMAScript® 2025 Language Specification
# sec-class-definitions

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
class

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Has more compatibility info.

参见