Inheritance
Extends and super.
A savings account is just like a normal account, but it also earns interest. Instead of copying all the code, we can make a new class that extends the old one, and only add what's different. That's inheritance.

- A savings account is an account
- Plus interest
- Extend, don't copy
extends and super
Savings extends account, so it gets all of account's properties and methods. In its constructor, super calls the parent's constructor first. Then it adds a rate, and a new method. And it can still use deposit, inherited from account. Run it.
class Account {
constructor(owner, balance) { this.owner = owner; this.balance = balance; }
deposit(n) { this.balance += n; }
}
class Savings extends Account {
constructor(owner, balance, rate) {
super(owner, balance);
this.rate = rate;
}
addInterest() { this.deposit(this.balance * this.rate); }
}
const s = new Savings("Ana", 1000, 0.05);
s.addInterest();
console.log(s.balance, s instanceof Account);1050 true
Use it carefully
Inheritance is useful when one thing really is a kind of another thing. A savings account is an account. But deep chains of classes extending classes get hard to follow. Many developers prefer small classes, and combining objects, instead of long inheritance chains.
| key | value |
|---|---|
| extends | inherit from a parent |
| super(...) | call the parent constructor |
| Override | redefine a method |
| Keep it | shallow |
Summary
Extends builds a class on top of another, and super calls the parent's constructor. Next, getters and static methods.
Key takeaways- class B extends A
- super() first
- Is-a relationships