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);// 公開メソッドで残高を取得: 12021console.log(account.getBalance());実行結果
120
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この JavaScript のコードで打つ記号と、出てくる回数です。
(× 11)× 11;× 9.× 9#× 5=× 5{× 4}× 4&× 2>× 2