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 | 116 +++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 files/ja/web/javascript/reference/operators/class/index.html (limited to 'files/ja/web/javascript/reference/operators/class/index.html') diff --git a/files/ja/web/javascript/reference/operators/class/index.html b/files/ja/web/javascript/reference/operators/class/index.html new file mode 100644 index 0000000000..289bba4253 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/class/index.html @@ -0,0 +1,116 @@ +--- +title: クラス式 +slug: Web/JavaScript/Reference/Operators/class +tags: + - Class + - Classes + - ECMAScript6 + - Expression + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/class +--- +
{{jsSidebar("Operators")}}
+ +

クラス式は、 ECMAScript 2015 でクラスを定義する方法の 1 つです。{{jsxref("Operators/function", "関数式", "", "true")}}と同じように、クラス式は名前を付けることも付けないこともできます。名前を付ける場合、クラス名はクラス内部のみのローカルです。

+ +

JavaScript のクラスはプロトタイプベースの継承が使われます。

+ +
{{EmbedInteractiveExample("pages/js/expressions-classexpression.html")}}
+ + + +

構文

+ +
const MyClass = class [className] [extends otherClassName] {
+    // クラス本体
+};
+ +

説明

+ +

クラス式の構文は、{{jsxref("Statements/class", "クラス宣言 (文)", "", "true")}} と似ています。 class 文では、 class 式の本体が{{jsxref("Strict_mode", "厳格モード", "", 1)}}で実行されます。

+ +

しかし、クラス式と{{jsxref("Statements/class", "クラス文", "", "true")}}はいくつかの相違点があります。

+ + + +

constructor メソッドは省略可能です。クラス式で生成されたクラスは、常に {{jsxref("Operators/typeof", "typeof")}} が "function" の値を返します。

+ +
'use strict';
+let Foo = class {};  // コンストラクタープロパティは省略可能
+Foo = class {};      // 再宣言が可能
+
+typeof Foo;             // "function" を返す
+typeof class {};        // "function" を返す
+
+Foo instanceof Object;   // true
+Foo instanceof Function; // true
+class Foo {}            // SyntaxError が発生 (クラス宣言は再宣言ができない)
+
+ +

+ +

簡単なクラス式

+ +

以下は、名前のない簡単なクラス式です。変数 Foo を使って参照できます。

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

名前付きクラス式

+ +

クラス内部で現在のクラスを参照したい場合は、名前付きクラス式を作成してください。この名前は、そのクラス式自身のスコープ内だけで見ることができます。

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

仕様書

+ + + + + + + + + + + + +
仕様書
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}
+ +

ブラウザーの互換性

+ + + +

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

+ +

関連情報

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