class 宣言は、プロトタイプベースの継承を使って、名前付きで新しいクラスを作成します。
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.
class 式を使ってクラスを定義することもできます。しかし、class 式と異なり、class 宣言は既存のクラスを再宣言できず、再宣言しようとすると型エラーになります。
構文
class name [extends] {
// class body
}
説明
class 式と同様、class 宣言の内部は strict モード で実行されます。コンストラクタプロパティはオプションです。
class 宣言は、(function 宣言と違って) hoisted されません。
例
単純な class 宣言
次の例では、はじめに Polygon という名前のクラスを定義し、次にそれを拡張して Square という名前のクラスを作成します。コンストラクタで使われている super() は、コンストラクタ内でのみ使えること、this キーワードの使用前に呼び出さなくてはならないことに注意してください。
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
}
2 度クラス宣言を行う
class 宣言を使って再度クラスを宣言すると、型エラーをスローします。
class Foo {};
class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
class 式を使って事前にクラスを定義していたときも、同じエラーをスローします。
var Foo = class {};
class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
仕様
ブラウザ実装状況
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.
Update compatibility data on GitHub
| デスクトップ | モバイル | サーバー | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
class | Chrome
完全対応
49
| Edge 完全対応 13 | Firefox 完全対応 45 | IE 未対応 なし | Opera 完全対応 36 | Safari 完全対応 10.1 | WebView Android
完全対応
49
| Chrome Android
完全対応
49
| Firefox Android 完全対応 45 | Opera Android ? | Safari iOS 完全対応 10.3 | Samsung Internet Android
完全対応
4.0
| nodejs 完全対応 6.0.0 |
凡例
- 完全対応
- 完全対応
- 未対応
- 未対応
- 実装状況不明
- 実装状況不明
- 実装ノートを参照してください。
- 実装ノートを参照してください。

