Classes
When you need many objects of the same shape, a class describes the shape once:
class Dog {
constructor(name) {
this.name = name;
this.tricks = [];
}
learn(trick) {
this.tricks.push(trick);
}
show() {
return `${this.name} knows ${this.tricks.length} tricks`;
}
}
const rex = new Dog("Rex");
rex.learn("sit");
console.log(rex.show()); // Rex knows 1 tricks
constructorruns when you writenew Dog(...). It sets up the new object.thisis the object being built or used.- Functions inside the class are methods, shared by every dog.
Inheritance
A class can extend another, getting all its methods and adding more:
class GuideDog extends Dog {
guide() {
return `${this.name} is guiding`;
}
}
A GuideDog can still learn and show. If the child needs its own constructor, it must call super(...) first to run the parent's.
Your task
- Write
class BankAccountwith:- a constructor taking
owner, startingbalanceat0, deposit(amount),withdraw(amount), which throwsnew Error("Insufficient funds")if there is not enough money (and leaves the balance unchanged).
- a constructor taking
- Write
class SavingsAccount extends BankAccountwithaddInterest(rate), which depositsbalance * rate.