Course outline · 0% complete

0/27 lessons0%

Course overview →

Inheritance: extends and super

lesson 3-3 · ~11 min · 8/27

extends links two prototypes

class Dog extends Animal chains the prototypes: Dog.prototype's own prototype becomes Animal.prototype. A lookup on a dog now walks: the instance, then Dog.prototype, then Animal.prototype. Same chain as lesson 3-1, just one link longer.

Two keywords come with it:

  • super(...) inside the constructor calls the parent constructor. A subclass constructor must call it before touching this.
  • super.method() inside a method calls the parent's version, useful when you override a method but still want the original behavior.

You will meet extends constantly even if you rarely write it: class HttpError extends Error, framework component classes, test doubles. Interviewers use it to check that you can trace the longer lookup chain and the super rules that come with it.

Code exercise · javascript

Run it. `Dog` overrides `speak` but reuses the parent's version through `super.speak()`. `instanceof` is true for both classes because both prototypes are on rex's chain.

Quiz

How does `rex instanceof Animal` decide its answer?

Quiz

In a subclass constructor you write `this.name = name;` BEFORE calling `super(...)`. What happens?

Interview note: prefer shallow hierarchies

Inheritance is a sharp tool. One level (Dog extends Animal) is fine. Deep trees get brittle, and interviewers like hearing that you know the alternative: composition, building objects out of smaller pieces (like the module pattern from lesson 1-3) instead of inheriting from a chain of ancestors. "Favor composition over inheritance" is a safe, correct instinct to voice.

Code exercise · javascript

Your turn. Extend `Rectangle` (given) with a class `Square` whose constructor takes ONE argument `side` and passes it to the parent as both width and height.