class

class

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

语法

var MyClass = class [className] [extends] {   // class body };

描述

类表达式与类声明(声明)具有类似的语法。但是,对于类表达式,您可以省略类名(“绑定标识符”),而不能使用类语句。此外,类表达式允许您重新定义/重新声明类,不要抛出任何类型错误,如类声明。构造函数属性是可选的。而且,typeof运算使用此关键字生成的类将永远是“功能”。

就像使用类语句一样,类表达式的类体以严格模式执行。

'use strict'; var Foo = class {}; // constructor property is optional var Foo = class {}; // Re-declaration is allowed typeof Foo; //returns "function" typeof class {}; //returns "function" Foo instanceof Object; // true Foo instanceof Function; // true class Foo {}; // Throws TypeError, doesn't allow re-declaration

示例

简单类表达式

这只是一个简单的匿名类表达式,您可以使用变量“Foo”来引用它。

var Foo = class { constructor() {} bar() { return 'Hello World!'; } }; var instance = new Foo( instance.bar( // "Hello World!" Foo.name; // "Foo"

命名的类表达式

如果要引用类体内的当前类,则可以创建一个已命名的类表达式。该名称仅在类表达式本身的范围内可见。

var Foo = class NamedFoo { constructor() {} whoIsThere() { return NamedFoo.name; } } var bar = new Foo( bar.whoIsThere( // "NamedFoo" NamedFoo.name; // ReferenceError: NamedFoo is not defined Foo.name; // "NamedFoo"

规范

SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Class definitions' in that specification.StandardInitial 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

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support42.0(Yes)45 (45)???

FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic supportNo support42.0(Yes)45.0 (45)???42.0