Lesson 11 of 14 · 10 min

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
  • constructor runs when you write new Dog(...). It sets up the new object.
  • this is 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

  1. Write class BankAccount with:
    • a constructor taking owner, starting balance at 0,
    • deposit(amount),
    • withdraw(amount), which throws new Error("Insufficient funds") if there is not enough money (and leaves the balance unchanged).
  2. Write class SavingsAccount extends BankAccount with addInterest(rate), which deposits balance * rate.
main.js
class BankAccount {
  constructor(owner) {
  }

  deposit(amount) {
  }

  withdraw(amount) {
  }
}

// class SavingsAccount ...

const account = new BankAccount("Chipo");
account.deposit(100);
account.withdraw(40);
console.log(account.balance);

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…