JavaScript の プライベートクラスフィールド

レベル 5371 打鍵

プライベートクラスフィールド(#付き)は真のカプセル化を提供し、クラス内からのみアクセス可能です。

JavaScript のコード

// #構文を使ったプライベートフィールドを持つクラス
1class BankAccount {
// プライベートフィールド - クラス外からアクセス不可
2 #balance = 0;
3
// depositメソッド - 検証して残高を更新
4 deposit(amount) {
5 if (amount > 0) this.#balance += amount;
// メソッドチェーンのためにthisを返す
6 return this;
7 }
8
// withdrawメソッド - 十分な資金を確認
9 withdraw(amount) {
10 if (amount > 0 && amount <= this.#balance) this.#balance -= amount;
11 return this;
12 }
13
// プライベートな残高の公開ゲッター
14 getBalance() {
15 return this.#balance;
16 }
17}
18
// アカウントを作成して操作をチェーン
19const account = new BankAccount();
20account.deposit(100).deposit(50).withdraw(30);
// 公開メソッドで残高を取得: 120
21console.log(account.getBalance());

実行結果

120
このコードでタイピング練習する

このコードでタイピング練習ができます。記録はランキングに反映されません。

このコードで使う記号

この JavaScript のコードで打つ記号と、出てくる回数です。

  • (× 11
  • )× 11
  • ;× 9
  • .× 9
  • #× 5
  • =× 5
  • {× 4
  • }× 4
  • &× 2
  • >× 2

JavaScript のレベル 5 のほかのコード例

← JavaScript タイピング練習のトップへ