将余额设为私有字段
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 23 课,共 56 课。
挑战
通过将 balance 转换为私有字段,让 BankAccount 类更安全。”
你的任务:
- 在类的顶部添加
#balance - 在构造函数中,将
this.balance改为this.#balance - 在所有方法中,将
this.balance改为this.#balance
亲手试试
import { BankAccount } from './bankAccount.js';
// 测试实现
const testAccount = new BankAccount('Alex Johnson', 500);
console.log(testAccount.getAccountInfo()); // "Alex Johnson: $500"
console.log('Balance:', testAccount.getBalance()); // 仍然有效:500
console.log('Balance:', testAccount.balance); // undefined
面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器