类表达式
类表达式是用来定义类的一种语法。和函数表达式相同的一点是,类表达式可以是命名也可以是匿名的。如果是命名类表达式,这个名字只能在类体内部才能访问到。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 (ECMA-262) Class definitions |
Living Standard |
浏览器兼容性
BCD tables only load in the browser