Question 32
Question
Answer
class BankAccount {
constructor(initialBalance) {
this[Symbol('balance')] = initialBalance; // Using Symbol as the key
}
deposit(amount) {
this[Symbol('balance')] += amount;
}
withdraw(amount) {
if (this[Symbol('balance')] >= amount) {
this[Symbol('balance')] -= amount;
return true; // Success
} else {
return false; // Insufficient funds
}
}
getBalance() {
return this[Symbol('balance')];
}
}
// Create an account
const myAccount = new BankAccount(100);
// Deposit and withdraw
myAccount.deposit(50);
console.log(myAccount.getBalance()); // Accessing the balance directly is harder
// Can't access directly through `myAccount.balance` or similar
Last updated