1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. 表达式和运算符
  5. 类表达式

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

类表达式

基线 广泛可用

自 2016年3月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

class 关键字可用于在表达式中定义类。类似于函数表达式,类表达式可以是命名的,也可以是匿名的。如果命名,则类的名称只能在类体内部才能访问到。

尝试一下

const Rectangle = class {
 constructor(height, width) {
 this.height = height;
 this.width = width;
 }
 area() {
 return this.height * this.width;
 }
};
console.log(new Rectangle(5, 8).area());
// Expected output: 40

语法

js
const MyClass = class [className] [extends otherClassName] {
 // class body
}

描述

类表达式的语法类似于类声明。与 class 声明一样,class 表达式的主体在严格模式下执行。

类表达式和类声明之间存在一些差异,但是:

  • 类表达式可以省略类名("绑定标识符"),这在类声明中是不可能的。
  • 类表达式允许你重新定义(重新声明)类而不会抛出 SyntaxError类声明不是这种情况。

constructor 方法是可选的。使用类表达式生成的类将始终响应 typeof 值为 "function"

js
"use strict";
let Foo = class {}; // constructor property is optional
Foo = class {}; // Re-declaration is allowed
typeof Foo; // returns "function"
typeof class {}; // returns "function"
Foo instanceof Object; // true
Foo instanceof Function; // true
class Foo {} // Throws SyntaxError (class declarations do not allow re-declaration)

示例

一个简单的类表达式

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

js
const Foo = class {
 constructor() {}
 bar() {
 return "Hello World!";
 }
};
const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"

命名类表达式

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

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"

规范

规范
ECMAScript® 2027 Language Specification
# sec-class-definitions

浏览器兼容性

参见

帮助改进 MDN

了解如何参与贡献

此页面最后更新于 ,由 MDN 贡献者更新。

AltStyle によって変換されたページ (->オリジナル) /