Menu
CoddyTech

存款和取款

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

challenge icon

挑战

接下来,我们通过实现 deposit() 和 withdraw() 方法,为你的 BankAccount 类添加交易功能。

你的任务是在 BankAccount 类中添加这两个新方法:

1. deposit(amount) 方法:

  • 检查 amount 是否为正数(大于 0)
  • 如果有效:
    • 将该金额加到余额中
    • 准确输出:Deposited $${amount}
  • 如果无效:准确输出:Invalid deposit amount

2. withdraw(amount) 方法:

  • 检查 amount 是否为正数,并且小于或等于当前余额
  • 如果有效:
    • 从余额中减去该金额
    • 准确输出:Withdrew $${amount}
  • 如果无效:准确输出:Invalid withdrawal amount or insufficient funds

亲手试试

import { BankAccount } from './bankAccount.js';

// 测试实现效果
const testAccount = new BankAccount('Alex Johnson', 500);

console.log('Initial state:');
console.log(testAccount.getAccountInfo()); // "Alex Johnson: $500"

testAccount.deposit(200);  // 输出:“Deposited $200”
console.log('New balance:', testAccount.getBalance()); // 700

testAccount.deposit(-50);  // 输出:“Invalid deposit amount”
console.log('Balance unchanged:', testAccount.getBalance()); // 600

testAccount.withdraw(100); // 输出:“Withdrew $100”
console.log('New balance:', testAccount.getBalance()); // 600

testAccount.withdraw(800); // 输出:“Invalid withdrawal amount or insufficient funds”
console.log('Balance unchanged:', testAccount.getBalance()); // 600




面向对象编程中的所有课

自己练习: JavaScript 在线编译器