Agyan
adda
Run
Reset
Copy
JavaScript Tutorial › JS Classes › Bank account class
Back to tutorial
Code
Edit, then press Run or Ctrl+Enter
<pre id="out"></pre> <script> class Account { constructor(owner, balance = 0) { this.owner = owner; this.balance = balance; } deposit(amount) { this.balance += amount; return this; } withdraw(amount) { if (amount > this.balance) throw new Error('Insufficient balance'); this.balance -= amount; return this; } toString() { return `${this.owner}: ₹${this.balance}`; } } class Savings extends Account { constructor(owner, balance, rate) { super(owner, balance); this.rate = rate; } addInterest() { return this.deposit(this.balance * this.rate / 100); } } const acc = new Savings('Ravi', 1000, 5); acc.deposit(500).addInterest(); let text = acc.toString(); try { acc.withdraw(99999); } catch (e) { text += '\n' + e.message; } document.getElementById('out').textContent = text; </script>
Result