此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
class
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年3月.
你也可以使用 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® 2026 Language Specification> # sec-class-definitions> |
浏览器兼容性
Enable JavaScript to view this browser compatibility table.