试一试
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
class {
// class body
}
class name {
// class body
}
描述
class 表达式与 class 声明非常相似,且语法几乎相同。与 class 声明一样,class 表达式的主体在 严格模式下执行。class 表达式和 class 声明之间的主要区别是类名,class 表达式中的类名可以省略以创建匿名类。类表达式允许你重新定义类,而使用 class 声明重新声明一个类会抛出 SyntaxError。有关更多信息,请参阅 类的章节。
示例
一个基本的类表达式
这是一个匿名的类表达式,你可以使用变量 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® 2026 语言规范 # sec-class-definitions |
浏览器兼容性
加载中…