MDN之Web 开发技术【class】

待我称王封你为后i 2021-07-05 02:46 544阅读 0赞

class 声明创建一个基于原型继承的具有给定名称的新类。

  1. class Polygon {
  2. constructor(height, width) {
  3. this.area = height * width;
  4. }
  5. }
  6. console.log(new Polygon(4,3).area);
  7. // expected output: 12

你也可以使用类表达式定义类。但是不同于类表达式,类声明不允许再次声明已经存在的类,否则将会抛出一个类型错误。

语法

  1. class name [extends] {
  2. // class body
  3. }

描述

和类表达式一样,类声明体在严格模式下运行。构造函数是可选的。

类声明不可以提升(这与函数声明不同)。

示例

声明一个类

在下面的例子中,我们首先定义一个名为Polygon的类,然后继承它来创建一个名为Square的类。注意,构造函数中使用的 super() 只能在构造函数中使用,并且必须在使用 this 关键字前调用。

  1. class Polygon {
  2. constructor(height, width) {
  3. this.name = 'Polygon';
  4. this.height = height;
  5. this.width = width;
  6. }
  7. }
  8. class Square extends Polygon {
  9. constructor(length) {
  10. super(length, length);
  11. this.name = 'Square';
  12. }
  13. }

重复定义类
重复声明一个类会引起类型错误。

  1. class Foo { };
  2. class Foo { };
  3. // Uncaught TypeError: Identifier 'Foo' has already been declared

若之前使用类表达式定义了一个类,则再次声明这个类同样会引起类型错误。

  1. let Foo = class { };
  2. class Foo { };
  3. // Uncaught TypeError: Identifier 'Foo' has already been declared

发表评论

表情:
评论列表 (有 0 条评论,544人围观)

还没有评论,来说两句吧...

相关阅读