Menu
CoddyTech

将余额设为私有字段

本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 23 课,共 56 课。

challenge icon

挑战

通过将 balance 转换为私有字段,让 BankAccount 类更安全。”

你的任务:

  1. 在类的顶部添加 #balance
  2. 在构造函数中,将 this.balance 改为 this.#balance
  3. 在所有方法中,将 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


面向对象编程中的所有课

自己练习: JavaScript 在线编译器