Sikau

Advanced JavaScript · Day 8 · about 25 min

Inheritance

extends, super and overriding.

A family of classes

A savings account is a bank account, with interest. Instead of copying code, a class can extend another, inherit everything, and add or change just what's different.

extends and super

class Shape {
  constructor(name) {
    this.name = name;
  }
  area() {
    return 0;
  }
  describe() {
    return `${this.name} with area ${this.area()}`;
  }
}

class Circle extends Shape {
  constructor(r) {
    super("Circle");
    this.r = r;
  }
  area() {
    return Math.round(Math.PI * this.r ** 2);
  }
}

const c = new Circle(2);
console.log(c.describe());
console.log(c instanceof Circle, c instanceof Shape);
class Animal {
  speak() {
    return "…";
  }
}
class Cat extends Animal {
  speak() {
    return super.speak() + " meow!";
  }
}
console.log(new Cat().speak());

Prefer short inheritance chains (one or two levels). Deep hierarchies get hard to follow; combining small objects is often simpler.

The rest of this lesson

  • Overriding and superexplain
  • Predict the outputpredict
  • Which speak?predict
  • Is-a or has-a?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript