クラス式

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.

クラス式は、 ECMAScript 2015 でクラスを定義する方法の 1 つです。関数式と同じように、クラス式は名前を付けることも付けないこともできます。名前を付けた場合、クラス名はクラス内部のみのローカルです。

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

試してみましょう

const Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  area() {
    return this.height * this.width;
  }
};

console.log(new Rectangle(5, 8).area());
// Expected output: 40

構文

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

解説

クラス式の構文は、クラス宣言(文) と似ています。 class 文では、 class 式の本体が厳格モードで実行されます。

しかし、クラス式とクラス文ではいくつかの相違点があります。

  • クラス式ではクラス名(「束縛識別子」 (binding identifier))を省略できますが、クラス文では省略できません。
  • クラス式は SyntaxError発生させずにクラスを再宣言することができます。これはクラス文の場合はできません。

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

js
"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 を使って参照できます。

js
const Foo = class {
  constructor() {}
  bar() {
    return "Hello World!";
  }
};

const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"

名前付きクラス式

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

js
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"

仕様書

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

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
class

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報