Classes and Inheritance

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

What you'll learn

Classes.js

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);

Step by step

  1. A class is a blueprint. Defining it creates no objects yet.
  2. JavaScript defines the class Savings.
  3. new Savings("Ada", 100): Savings has no constructor of its own, so the one from Account runs, with this = the new object.
  4. A new key owner with the value "Ada" is added to the Savings object.
  5. A new key balance with the value 100 is added to the Savings object.
  6. acc points to the new Savings object.
  7. acc.deposit(50): Savings has no deposit, so JavaScript finds it on Account, the parent class.
  8. balance in the Savings that acc points to changes from 100 to 150.
  9. deposit returns 150.
  10. Account.deposit() has finished, so its variables are gone.
  11. addInterest is Savings's own method.
  12. interest is created with the value 15.
  13. this.deposit(interest) calls the inherited method on the same object.
  14. balance in the Savings that acc points to changes from 150 to 165.
  15. deposit returns 165.
  16. addInterest returns 165.
  17. Savings.addInterest() has finished, so its variables are gone.
  18. 165, and acc is an Account too: a Savings is a kind of Account.

Common mistakes

Best practices

Key takeaways

Check yourself

Account.deposit is found for a Savings object because?

Answer: Savings extends Account

acc instanceof Account?

Answer: true

·

More in Objects and Arrays