1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. 语句和声明
  5. class

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

View in English Always switch to English

class

基线 广泛可用

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

class 声明创建一个绑定到给定名称的新

你也可以使用 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;
 }
}

规范

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

浏览器兼容性

参见

帮助改进 MDN

了解如何参与贡献

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

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