首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

class

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

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

语法

代码语言:javascript
复制
class name [extends] {
  // class body
}

描述

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

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

示例

声明一个类

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

代码语言:javascript
复制
class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
}

class Square extends Polygon {
  constructor(length) {
    super(length, length);
?   this.name = 'Square';
  }
}

重复定义类

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

代码语言:javascript
复制
class Foo {};
class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared

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

代码语言:javascript
复制
var Foo = class {};
class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Class definitions' in that specification.

Standard

Initial definition.

ECMAScript 2016 (ECMA-262)The definition of 'Class definitions' in that specification.

Standard

?

ECMAScript 2017 (ECMA-262)The definition of 'Class definitions' in that specification.

Standard

?

ECMAScript Latest Draft (ECMA-262)The definition of 'Class definitions' in that specification.

Living Standard

?

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

42.0

(Yes)

45 (45)

?

?

10.1

Array subclassing

43.0

?

No support

?

?

?

Allowed in sloppy mode

49.0

?

?

?

?

?

Feature

Android

Android Webview

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Chrome for Android

Basic support

No support

42.0

(Yes)

45.0 (45)

?

?

?

42.0

Array subclassing

No support

43.0

?

No support

?

?

?

43.0

Allowed in sloppy mode

No support

49.0

?

?

?

?

?

49.0

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com