Menu
Coddy logo textTech

静的プロパティ

CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 32/56。

静的プロパティは、クラスのインスタンスではなく、クラス自体に属します。これらはすべてのインスタンス間で共有されます。

静的プロパティを持つクラスを定義します:

class Counter {
  // 静的プロパティを定義します
  static count = 0;
  
  constructor() {
    // 新しいインスタンスが作成されるたびに静的なcountをインクリメントします
    Counter.count++;
  }
}

クラス名を使用して静的プロパティにアクセスします:

console.log(Counter.count); // 0

// インスタンスをいくつか作成します
const counter1 = new Counter();
const counter2 = new Counter();

console.log(Counter.count); // 2

静的プロパティは、すべてのインスタンスで共有されるべき値や、クラスレベルの定数に便利です。例えば:

class MathConstants {
  static GOLDEN_RATIO = 1.61803;
}

console.log(MathConstants.PI); // 3.14159
challenge icon

チャレンジ

MathConstants クラスに静的プロパティ PIE を追加します:

  1. 静적プロパティ PI3.14159 に設定します
  2. 静的プロパティ E2.71828 に設定します

チートシート

静的プロパティは、インスタンスではなくクラス自体に属します。これらはすべてのインスタンス間で共有され、クラス名を使用してアクセスされます。

staticキーワードを使用して静的プロパティを定義します。

class Counter {
  static count = 0;
  
  constructor() {
    Counter.count++;
  }
}

クラス名を通じて静的プロパティにアクセスします:

console.log(Counter.count); // 0

const counter1 = new Counter();
const counter2 = new Counter();

console.log(Counter.count); // 2

静的プロパティは、クラスレベルの定数に便利です:

class MathConstants {
  static PI = 3.14159;
  static E = 2.71828;
}

console.log(MathConstants.PI); // 3.14159

自分で試してみよう

import { MathConstants } from './constants.js';

// テストコード - 変更しないでください
console.log(MathConstants.PI);        // 3.14159 と出力されるはずです
console.log(MathConstants.E);         // 2.71828 と出力されるはずです
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン