上級 › プライベートフィールド外部アクセスの構文エラー原因 › パターン5
プライベートフィールド外部アクセスの構文エラー原因
#で始まるプライベートフィールドを、宣言したクラスの外からドットで直接読み書きしようとしたときに出るエラーです。
1 class Score { 2 #points = 0; 3 add(n) { this.#points += n; } 4 getPoints() { return this.#points; } 5 } 6 const s = new Score(); 7 s.add(5); 8 console.log(_____________); ^
main.js:8
console.log(s.#points);
^
SyntaxError: Private field '#points' must be declared in an enclosing class
空欄を埋めて実行を通す
#pointsは宣言したクラスの中でしか読み書きできません。外部への公開はgetPoints()のようなメソッドで行います。
次の問題