class
Baseline
広く利用可能
この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。2017年3月以降、すべてのブラウザーで利用可能です。
class 宣言は、指定された名前の新しい class を作成します。
クラス式 を使ってクラスを定義できます。
試してみましょう
class Polygon {
constructor(height, width) {
this.area = height * width;
}
}
console.log(new Polygon(4, 3).area);
// 予想される結果: 12
構文
js
class name {
// クラス本体
}
class name extends otherName {
// クラス本体
}
解説
クラス宣言のクラス本体は 厳格モード で実行されます。クラス宣言は let と非常によく似ています。
-
class宣言は、関数だけでなくブロックにもスコープされます。 -
class宣言は、宣言された場所に到達した後にのみアクセスできます(一時的デッドゾーン を参照)。このため、class宣言は一般的に 非ホイスティング とみなされます(関数宣言 とは異なります)。 -
スクリプトの最上位レベルで宣言された
class宣言は、globalThisにプロパティを作成しません(関数宣言 とは異なります)。 -
class宣言は、同じスコープ内の他の宣言によって 再宣言 できません。
js
class Foo {
static {
Foo = 1; // TypeError: Assignment to constant variable.
}
}
class Foo2 {
bar = (Foo2 = 1); // TypeError: Assignment to constant variable.
}
class Foo3 {}
Foo3 = 1;
console.log(Foo3); // 1
例
>クラス宣言
次の例では、はじめに Rectangle という名前のクラスを定義し、次にそれを拡張して FilledRectangle という名前のクラスを作成します。
なお、コンストラクター (constructor) で使われている super() は、コンストラクター内でのみ使えること、 this キーワードの使用前に呼び出さなくてはならないことに注意してください。
js
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
}
class FilledRectangle extends Rectangle {
constructor(height, width, color) {
super(height, width);
this.name = "Filled rectangle";
this.color = color;
}
}
仕様書
| 仕様書 |
|---|
| ECMAScript® 2027 Language Specification> # sec-class-definitions> |