类表达式

class 关键字可用于在表达式内定义类。

¥The class keyword can be used to define a class inside an expression.

你还可以使用 class 声明

¥You can also define classes using the class declaration.

Try it

语法

¥Syntax

js
class {
  // class body
}
class name {
  // class body
}

注意:表达式语句 不能以关键字 class 开头,以避免与 class 声明 产生歧义。class 关键字仅在出现在无法接受语句的上下文中时才开始表达式。

¥Note: An expression statement cannot begin with the keyword class to avoid ambiguity with a class declaration. The class keyword only begins an expression when it appears in a context that cannot accept statements.

描述

¥Description

class 表达式与 class 声明 非常相似,并且具有几乎相同的语法。与 class 声明一样,class 表达式的主体在 严格模式 中执行。class 表达式和 class 声明之间的主要区别在于类名,在 class 表达式中可以省略类名以创建匿名类。类表达式允许你重新定义类,而使用 class 声明重新声明类会抛出 SyntaxError。另请参阅有关 classes 的章节以获取更多信息。

¥A class expression is very similar to, and has almost the same syntax as, a class declaration. As with class declarations, the body of a class expression is executed in strict mode. The main difference between a class expression and a class declaration is the class name, which can be omitted in class expressions to create anonymous classes. Class expressions allow you to redefine classes, while redeclaring a class using class declarations throws a SyntaxError. See also the chapter about classes for more information.

示例

¥Examples

一个简单的类表达式

¥A simple class expression

这只是一个简单的匿名类表达式,你可以使用变量 Foo 来引用它。

¥This is just a simple anonymous class expression which you can refer to using the variable Foo.

js
const Foo = class {
  constructor() {}
  bar() {
    return "Hello World!";
  }
};

const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"

命名类表达式

¥Named class expressions

如果要在类主体中引用当前类,可以创建命名类表达式。该名称仅在类表达式本身的范围内可见。

¥If you want to refer to the current class inside the class body, you can create a named class expression. The name is only visible within the scope of the class expression itself.

js
const Foo = class NamedFoo {
  constructor() {}
  whoIsThere() {
    return NamedFoo.name;
  }
};
const bar = new Foo();
bar.whoIsThere(); // "NamedFoo"
NamedFoo.name; // ReferenceError: NamedFoo is not defined
Foo.name; // "NamedFoo"

规范

Specification
ECMAScript Language Specification
# sec-class-definitions

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also