From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../reference/operators/class/index.html | 112 +++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/operators/class/index.html (limited to 'files/zh-cn/web/javascript/reference/operators/class/index.html') diff --git a/files/zh-cn/web/javascript/reference/operators/class/index.html b/files/zh-cn/web/javascript/reference/operators/class/index.html new file mode 100644 index 0000000000..739c651513 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/class/index.html @@ -0,0 +1,112 @@ +--- +title: 类表达式 +slug: Web/JavaScript/Reference/Operators/class +tags: + - Class + - Classes + - ES6 +translation_of: Web/JavaScript/Reference/Operators/class +--- +
{{jsSidebar("Operators")}}
+ +

类表达式是用来定义类的一种语法。和函数表达式相同的一点是,类表达式可以是命名也可以是匿名的。如果是命名类表达式,这个名字只能在类体内部才能访问到。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"
+
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}}
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}}
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.operators.class")}}

+ +

相关链接

+ + -- cgit v1.2.3-54-g00ecf