AI Hints
JavaScript · Lesson 72 of 138

Inheritance

Extends and super.

⏱ 2 min read▶ Video at 1:27:45🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Inheritance
From the video: 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.

app.jsjavascript
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);
Output
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.

keyvalue
extendsinherit from a parent
super(...)call the parent constructor
Overrideredefine a method
Keep itshallow

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
Next up: Getters and Static — computed and shared