Menu
Coddy logo textTech

入金と出金

CoddyのJavaScriptジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 22/56。

challenge icon

チャレンジ

次に、deposit() メソッドと withdraw() メソッドを実装して、BankAccount クラスに取引機能を追加します。

あなたのタスクは、BankAccount クラスにこれら2つの新しいメソッドを追加することです:

1. <strong>deposit(amount)</strong> メソッド:

  • amount が正(0より大きい)であるかチェックします
  • 有効な場合:
    • 残高に金額を加算します
    • 次のように正確にログを出力します: Deposited ${amount}
  • 無効な場合: 次のように正確にログを出力します: Invalid deposit amount

2. <strong>withdraw(amount)</strong> メソッド:

  • 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




オブジェクト指向プログラミングのすべてのレッスン