类表达式

类表达式是用来定义类的一种语法。和函数表达式相同的一点是,类表达式可以是命名也可以是匿名的。如果是命名类表达式,这个名字只能在类体内部才能访问到。JavaScript 的类也是基于原型继承的。

语法

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

描述

类表达式的语法和类语句的语法很类似,只是在类表达式中,你可以省略掉类名,而类语句中不能。

和类声明一样,类表达式中的代码也是强制严格模式的。

示例

使用类表达式

下面的代码使用类表达式语法创建了一个匿名类,然后赋值给变量 Foo。

let Foo = class {
  constructor() {}
  bar() {
    return "Hello World!";
  }
};

let instance = new Foo();
instance.bar(); 
// "Hello World!"

命名类表达式

如果你想在类体内部也能引用这个类本身,那么你就可以使用命名类表达式,并且这个类名只能在类体内部访问。

const Foo = class NamedFoo {
  constructor() {}
  whoIsThere() {
    return NamedFoo.name;
  }
}

let bar = new Foo();

bar.whoIsThere(); 
// "NamedFoo"

NamedFoo.name; 
// ReferenceError: NamedFoo is not defined

Foo.name; 
// "NamedFoo"

规范

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
Class definitions
Standard Initial definition.
ECMAScript 2016 (ECMA-262)
Class definitions
Standard
ECMAScript 2017 (ECMA-262)
Class definitions
Standard
ECMAScript Latest Draft (ECMA-262)
Class definitions
Draft

浏览器兼容性

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
class Chrome Full support 42 Edge Full support 13 Firefox Full support 45 IE No support No Opera Full support Yes Safari Full support Yes WebView Android Full support 42 Chrome Android Full support 42 Firefox Android Full support 45 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support 4.0 nodejs Full support 6.0.0
Full support 6.0.0
Full support 5.0.0
Disabled
Disabled From version 5.0.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

相关链接