×

javascript · level 3 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

lets one class inherit everything from another.

An ebook is a product with a download. Rather than copy every method, write class Ebook extends Product. This is : the child class gets all of the parent's methods for free.

A child with its own constructor must call first, which runs the parent's constructor. To change an inherited method, it by writing one with the same name. Inside it, super.label() still reaches the parent's version, so you can build on it.

class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
  label() { return `${this.name}: £${this.price}`; }
}
class Ebook extends Product {
  label() { return `${super.label()} (download)`; }
}
const shelf = [new Product("Mug", 8), new Ebook("Recipes", 5)];
for (const item of shelf) { console.log(item.label()); }

Ebook has no constructor of its own, so JavaScript passes its arguments straight to the one in Product.