上級 › インスタンス全体で共有したい値をstaticにし忘れる › パターン5
インスタンス全体で共有したい値をstaticにし忘れる
クラスのインスタンスをまたいで値を共有したい場合はstaticフィールドが必要です。
1 class Cache { 2 ______ store = {}; ^ 3 static set(key, value) { 4 Cache.store[key] = value; 5 } 6 } 7 Cache.set("a", 1); 8 console.log(Object.keys(Cache.store).length);
main.js:4
Cache.store[key] = value;
^
TypeError: Cannot set properties of undefined (setting 'a')
空欄を埋めて実行を通す
storeをstaticにしないと、Cache.storeはクラス自身には存在せずundefinedのままです。
次の問題