A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/class below:

class - JavaScript | MDN

class

Baseline Widely available

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

你也可以使用 class 表达式来定义类。

尝试一下
class Polygon {
  constructor(height, width) {
    this.area = height * width;
  }
}

console.log(new Polygon(4, 3).area);
// Expected output: 12
语法
class name {
  // 类体
}
class name extends otherName {
  // 类体
}
描述

类声明的类体在严格模式下执行。class 声明与 let 非常相似:

在类体外部,class 声明可以像 let 一样被重新赋值,但你应该避免这样做。在类体内部,类的绑定是常量,就像 const 一样。

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 关键字之前调用。

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;
  }
}
规范 浏览器兼容性 参见

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4