Make objects from a class with a constructor and methods, then extend it with a subclass that adds a method.
JavaScript · beginner · 8 min · 18 steps · free
class Account {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
return this.balance;
}
}
class Savings extends Account {
addInterest(rate) {
const interest = this.balance * rate;
return this.deposit(interest);
}
}
const acc = new Savings('Ada', 100);
acc.deposit(50);
acc.addInterest(0.1);
console.log(acc.balance, acc instanceof Account);Savings.new Savings("Ada", 100): Savings has no constructor of its own, so the one from Account runs, with this = the new object.owner with the value "Ada" is added to the Savings object.balance with the value 100 is added to the Savings object.acc points to the new Savings object.acc.deposit(50): Savings has no deposit, so JavaScript finds it on Account, the parent class.balance in the Savings that acc points to changes from 100 to 150.deposit returns 150.Account.deposit() has finished, so its variables are gone.interest is created with the value 15.this.deposit(interest) calls the inherited method on the same object.balance in the Savings that acc points to changes from 150 to 165.deposit returns 165.addInterest returns 165.Savings.addInterest() has finished, so its variables are gone.Answer: Savings extends Account
Answer: true
← Destructuring and Spread · How this Works →