class

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2016.

We'd love to hear more about your role and the company you work for
Please help us by answering a few questions.

class 宣言は、プロトタイプベースの継承を使って、指定された名前の新しいクラスを作成します。

クラス式を使ってクラスを定義することもで、その場合は再定義やクラス名の省略ができます。同じスコープでクラス宣言を同じ名前で行おうとすると、SyntaxError が発生します。

試してみましょう

class Polygon {
  constructor(height, width) {
    this.area = height * width;
  }
}

console.log(new Polygon(4, 3).area);
// Expected output: 12

構文

js
class name [extends otherName] {
  // クラス本体
}

解説

クラス式と同様、クラス宣言の内部は厳格モードで実行されます。constructor メソッドは省略可能です。

クラス宣言は letconst と同様に動作し、巻き上げが行われません(関数宣言とは異なります)。

単純なクラス宣言

次の例では、はじめに 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;
  }
}

クラスを二度宣言しようとする

クラス宣言を使って再度クラスを宣言すると、 SyntaxError が発生します。

js
class Foo {}
class Foo {} // Uncaught SyntaxError: Identifier 'Foo' has already been declared

クラス式を使って事前にクラスを定義していたときも、同じエラーが発生します。

js
let Foo = class {};
class Foo {} // Uncaught SyntaxError: Identifier 'Foo' has already been declared

Firefox のウェブコンソール (ツール > ウェブ開発者 > ウェブコンソール) などの REPL で実験しているときに、同じ名前のクラス宣言を 2 つの入力で実行すると、同じ再宣言エラーが発生することがあります。この課題については、Firefox bug 1580891で詳しく議論されていますので、ご覧ください。Chrome コンソールでは、異なる REPL 入力間でのクラスの再宣言が可能です。

仕様書

Specification
ECMAScript® 2025 Language Specification
# sec-class-definitions

ブラウザーの互換性

関連情報