チャレンジ:クラスでプライベートプロパティを実装する
メニューを表示するにはスワイプしてください
課題
ユーザーの銀行口座を安全に管理するために、BankAccount クラスを作成します。各口座には所有者と残高がありますが、残高は直接アクセスできないように保護したいと考えています。目的は、プライベートプロパティを使用して残高への意図しない変更を防ぎ、メソッドを通じて制御されたアクセスのみを許可することです。
- プライベート残高プロパティ:
BankAccountクラス内でプライベートプロパティ#balanceを宣言します。
- コンストラクタ:
- コンストラクタは
ownerとinitialBalanceをパラメータとして受け取ります; ownerをパブリックプロパティに、initialBalanceをプライベートプロパティ#balanceに代入します。
- コンストラクタは
- メソッドの追加:
- deposit: パラメータとして
amountを受け取るメソッドを定義します。amountが0より大きい場合、#balanceにamountを加算します; - withdraw: パラメータとして amount を受け取るメソッドを定義します。amount が0より大きく、かつ
#balance以下の場合、amountを#balanceから減算します; - getBalance: 所有者の名前と口座残高を含む文字列(例:
"Account balance for John: $1500")を返すメソッドを定義します。
- deposit: パラメータとして
123456789101112131415161718192021222324252627282930313233343536class BankAccount { #_____; // Declare private property constructor(owner, initialBalance) { this._____ = owner; this.#_____ = initialBalance; } deposit(_____) { if (_____) { this.#_____ += _____; } } withdraw(_____) { if (_____ && _____) { this.#_____ -= _____; } } getBalance() { return `Account balance for ${this._____}: $${this.#_____}`; } } // Testing const account1 = new BankAccount('Alice', 1000); account1.deposit(500); console.log(account1.getBalance()); // Expected: Account balance for Alice: $1500 account1.withdraw(300); console.log(account1.getBalance()); // Expected: Account balance for Alice: $1200 // Attempt direct access (should cause an error) // console.log(account1.#balance);
#balanceクラスでプライベートプロパティBankAccountを宣言します;- コンストラクタで
ownerをパブリックプロパティに、initialBalanceをプライベートプロパティ#balanceに代入します; depositメソッドを定義し、パラメータとしてamountを受け取ります。amountが0より大きい場合、amountに#balanceを加算します;withdrawメソッドを定義し、パラメータとしてamountを受け取ります。amountが0より大きく、かつ#balance以下の場合、amountを#balanceから減算します;getBalanceメソッドを定義し、所有者の名前と口座残高を返す文字列を返します。
123456789101112131415161718192021222324252627282930313233343536class BankAccount { #balance; // Declare private property constructor(owner, initialBalance) { this.owner = owner; this.#balance = initialBalance; } deposit(amount) { if (amount > 0) { this.#balance += amount; } } withdraw(amount) { if (amount > 0 && amount <= this.#balance) { this.#balance -= amount; } } getBalance() { return `Account balance for ${this.owner}: $${this.#balance}`; } } // Testing const account1 = new BankAccount('Alice', 1000); account1.deposit(500); console.log(account1.getBalance()); // Output: Account balance for Alice: $1500 account1.withdraw(300); console.log(account1.getBalance()); // Output: Account balance for Alice: $1200 // Attempt direct access (should cause an error) // console.log(account1.#balance);
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 8
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 8