Menu
CoddyTech

入金と出金

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

challenge icon

チャレンジ

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

BankAccount クラスに次の2つのメソッドを追加してください。

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オンラインコンパイラ