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 2017.

class 声明为给定名称创建新 classbinding

¥The class declaration creates a binding of a new class to a given name.

你还可以使用 class 表达

¥You can also define classes using the class expression.

Try it

语法

¥Syntax

js
class name {
  // class body
}
class name extends otherName {
  // class body
}

描述

¥Description

类声明的类体在 严格模式 中执行。class 声明与 let 非常相似:

¥The class body of a class declaration is executed in strict mode. The class declaration is very similar to let:

  • class 声明的作用域为块和函数。
  • class 声明只能在到达声明位置后才能访问(参见 颞死区)。因此,class 声明通常被视为 non-hoisted(与 函数声明 不同)。
  • 当在脚本的顶层声明时,class 声明不会在 globalThis 上创建属性(与 函数声明 不同)。
  • class 声明不能被同一范围内的任何其他声明成为 redeclared

在类体之外,可以像 let 一样重新分配 class 声明,但应避免这样做。在类体内,绑定像 const 一样是常量。

¥Outside the class body, class declarations can be re-assigned like let, but you should avoid doing so. Within the class body, the binding is constant like 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

示例

¥Examples

一个简单的类声明

¥A simple class declaration

在下面的示例中,我们首先定义一个名为 Rectangle 的类,然后扩展它以创建一个名为 FilledRectangle 的类。

¥In the following example, we first define a class named Rectangle, then extend it to create a class named FilledRectangle.

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

¥Note that super(), used in the constructor, can only be used in constructors, and must be called before the this keyword can be used.

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;
  }
}

规范

Specification
ECMAScript Language Specification
# sec-class-definitions

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看