class 式は、ECMAScript 2015 でクラスを定義する方法の 1 つです。function 式と同じように、class 式は名前を付けることも付けないこともできます。名前を付ける場合、クラス名はクラス内部のみローカルです。 JavaScript のクラスはプロトタイプベースの継承が使われます。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
構文
var MyClass = class [className] [extends] { // class body };
説明
class 式の構文は、class 文(宣言) と似ています。ただし、class 式ではクラス名 (束縛識別子; "binding identifier") を省略できますが、class 文では省略できません。また、class 式は、class の再定義/再宣言が可能で、class 文 のように型エラーをスローしません。コンストラクタプロパティはオプションです。また、このキーワードを使って生成したクラスの typeof は常に "functions" になります。
class 文のように、class 式のクラス内部は strict モード で実行されます。
'use strict';
var Foo = class {}; // コンストラクタプロパティはオプション
var Foo = class {}; // 再宣言は可能
typeof Foo; // "function" を返す
typeof class {}; // "function" を返す
Foo instanceof Object; // true
Foo instanceof Function; // true
class Foo {}; // 再宣言は不可能で、TypeError を投げる
例
簡単な class 式
以下は、名前のない簡単な class 式です。変数 "Foo" を使って参照できます。
var Foo = class {
constructor() {}
bar() {
return "Hello World!";
}
};
var instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"
名前付き class 式
クラス内部で現在のクラスを参照したい場合は、名前付きクラス式を作成してください。この名前は、その class 式自身のスコープ内でだけ見えます。
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"
仕様
ブラウザ実装状況
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| デスクトップ | モバイル | サーバー | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
class | Chrome 完全対応 42 | Edge 完全対応 あり | Firefox 完全対応 45 | IE 未対応 なし | Opera 完全対応 あり | Safari 完全対応 あり | WebView Android 完全対応 42 | Chrome Android 完全対応 42 | Edge Mobile 完全対応 あり | Firefox Android 完全対応 45 | Opera Android 完全対応 あり | Safari iOS 完全対応 あり | Samsung Internet Android 完全対応 4.0 | nodejs
完全対応
6.0.0
|
凡例
- 完全対応
- 完全対応
- 未対応
- 未対応
- ユーザーが明示的にこの機能を有効にしなければなりません。
- ユーザーが明示的にこの機能を有効にしなければなりません。