Thuta Learning
JavaScript
IntermediateProgrammingBeginner

Inheritance

JavaScriptLesson 1725 min

What you'll walk away with

  • Write a child class that reuses a parent's methods through extends
  • Explain why a child constructor must call super() before touching this
  • Override a method and reuse the parent's behavior with super.method()
  • Use the "is-a" test to choose between inheritance and composition

Explain it simply

Explain it simply

Every animal has a name and can make a sound. A dog is an animal, so it has all of that, plus things only dogs do, like fetching a ball. Inheritance is how you write that "a Dog is a kind of Animal" relationship in code.

In JavaScript, class Dog extends Animal gives Dog every Animal method without copying a single line. Where Dog should behave differently, such as speak, you write a method with the same name and give it the dog's own version.

Problem → Why → Solution

The problem: a fix lands in only half of the copied code

An app has two notification classes, email and SMS, and the recipient check is copied into both. A bug fix that rejects an empty recipient was added to EmailNotification, but nobody remembered SmsNotification. The result: SMS messages addressed to nobody vanish without an error.

notifications.js
class EmailNotification {
  constructor(to) {
    if (!to) throw new Error("Recipient required"); // fixed here...
    this.to = to;
  }
  describe() { return `Notification for ${this.to}`; }
}

class SmsNotification {
  constructor(to) {
    this.to = to;                                    // ...but not here
  }
  describe() { return `Notification for ${this.to}`; } // copied again
}

new SmsNotification(""); // no error: an SMS to nobody

Why does this happen?

Both classes share the part that makes them notifications, but that part is copied instead of living in one place. Move the shared logic into a Notification parent class, have both classes extend it, and a single fix reaches every child at once.

Core concept: extends, super and overriding

class Dog extends Animal makes two links. Dog.prototype is linked to Animal.prototype, so dog objects find Animal's instance methods, and Dog itself is linked to Animal, so static methods are inherited too. When you call dog.speak(), JavaScript looks on dog first, then on Dog.prototype, then on Animal.prototype, and uses the first match it finds.

text
Method lookup for dog.speak() and dog.toString()
------------------------------------------------
dog                 own data: name, breed
 |
 v  [[Prototype]]
Dog.prototype       speak(), fetch()     <- speak found here first
 |
 v
Animal.prototype    speak()              <- hidden by Dog's speak
 |
 v
Object.prototype    toString(), hasOwnProperty()

If a child class has a constructor, it must call super(...) before it uses this. In a derived class the parent constructor creates and initialises the object, so before super() returns there is no this at all; writing this.breed = breed above super() throws a ReferenceError. If the child has no constructor, JavaScript supplies a default one that passes every argument straight to super().

Writing a method in the child with the same name as one in the parent is called overriding: the child's version hides the parent's. To add to the parent's behavior instead of replacing it, call super.speak() from inside the method. Use inheritance only for a genuine is-a relationship, "a Dog is an Animal", with a stable parent contract. For a has-a relationship, "a Car has an Engine", use composition: store the other object as a property.

To ask whether an object belongs to a class family, use instanceof. dog instanceof Animal checks whether Animal.prototype appears anywhere on dog's prototype chain, so it is true. Every extra level of inheritance makes that chain one step longer, and a change to a parent affects every child below it. That is why hierarchies deeper than two or three levels become hard to follow and scary to change.

Mental model: look in the child, then climb
  1. Child constructor calls super() first
  2. Parent sets up this
  3. Method lookup starts at the child
  4. Not found? Climb to the parent

The child's method always wins; reaching the parent's version takes an explicit super.method().

General pattern

javascript
class Child extends Parent {
  constructor(parentArg, childArg) {
    super(parentArg);          // must come before this
    this.extra = childArg;
  }

  sharedMethod() {             // override
    const base = super.sharedMethod();
    return base + " plus child behavior";
  }
}

extends links Child to Parent, and super(parentArg) runs the parent constructor. A method with the same name is an override, and super.sharedMethod() fetches the parent's result to build on.

Example: Animal, Dog and Cat

Animal provides name and speak(), and Dog and Cat override speak() in their own way. Dog also adds a brand-new fetch() method, and the last line checks the relationships with instanceof. Before running it, predict which speak() each object will use.

animals.js
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // call the parent constructor first
    this.breed = breed;
  }

  speak() {
    return `${this.name} barks: Woof!`;
  }

  fetch() {
    return `${this.name} is fetching the ball`;
  }
}

class Cat extends Animal {
  constructor(name, color) {
    super(name);
    this.color = color;
  }

  speak() {
    return `${this.name} meows: Meow!`;
  }
}

const dog = new Dog("Buddy", "Golden Retriever");
const cat = new Cat("Whiskers", "Orange");

console.log(dog.speak());
console.log(dog.fetch());
console.log(cat.speak());
console.log(dog instanceof Animal, cat instanceof Dog);

Code breakdown

  1. Line 11class Dog extends Animal {

    Dog.prototype is now linked to Animal.prototype, so any method Dog does not define is borrowed from Animal.

  2. Line 13super(name); // call the parent constructor first

    Runs Animal's constructor, which sets this.name. Touching this before this line would throw a ReferenceError.

  3. Line 14this.breed = breed;

    Only after super() can the constructor use this, adding the dog-only breed property.

  4. Lines 17-19speak() {

    Overrides Animal's speak(). Lookup finds this version on Dog.prototype first, so dog.speak() says "barks: Woof!" rather than "makes a sound".

  5. Line 43console.log(dog instanceof Animal, cat instanceof Dog);

    instanceof walks the prototype chain. Animal.prototype is on dog's chain, so the first is true; Cat and Dog are only siblings, so cat instanceof Dog is false.

You should see
Buddy barks: Woof!
Buddy is fetching the ball
Whiskers meows: Meow!
true false

Overriding while still using the parent

An override does not have to throw the parent's work away. UrgentNotification below upper-cases the message and hands the rest of the formatting to super.send(). If the parent's format ever changes, the child follows automatically. Notice that UrgentNotification has no constructor: the default one forwards "ops@example.com" to the parent, which sets this.to. Inside super.send(), this is still the UrgentNotification instance.

urgent.js
class Notification {
  constructor(to) { this.to = to; }
  send(text) { return `To ${this.to}: ${text}`; }
}

class UrgentNotification extends Notification {
  send(text) {
    return super.send(text.toUpperCase() + "!");
  }
}

console.log(new UrgentNotification("ops@example.com").send("disk full"));
// To ops@example.com: DISK FULL!

In real projects

Where this shows up in real projects

In a notification system, a Notification base class handles recipient checks, retries and logging in one place, while EmailNotification and SmsNotification override only deliver(). Supporting push notifications later means one new class that extends the base and writes deliver().

You meet extends all over the JavaScript ecosystem. Custom errors are written as class ValidationError extends Error, as later lessons show, and browser Web Components as class MyButton extends HTMLElement. Older React projects contain class components that extend React.Component. In every case the child honours the parent's contract and overrides only the methods it needs.

When reviewing inheritance, ask: "Can a child be used anywhere the parent is expected and still work?" If a function like sendAll(notifications) handles any kind of Notification without trouble, the hierarchy is healthy. If one child forces special cases such as if (n instanceof SmsNotification), it is time to rethink the design.

Common mistakes

Common mistakes

1. Using this before super()

constructor(name, breed) { this.breed = breed; super(name); } throws "ReferenceError: Must call super constructor in derived class before accessing 'this'". The easy rule is to make super() the first statement. Finishing the constructor without ever calling super() is also a ReferenceError.

2. Accidentally discarding the parent's work in an override

Suppose the parent's send() validates the recipient and writes a log entry. If a child rewrites send() and never calls super.send(), the validation and logging silently disappear. For every override, decide on purpose whether you are replacing the parent's work or extending it.

3. Extending just to reuse code when it is not is-a

class Stack extends Array gives you push and pop, but also splice(), shift() and stack[0] = ..., all of which break the stack's last-in, first-out rule. Keeping a private #items array inside Stack and exposing only push and pop, which is composition, is far safer.

Best practices

Best practices

  • Keep hierarchies shallow: one base class and one level of children is usually enough.
  • Make super() the first line of a child constructor and add the child-only fields below it.
  • Declare the methods children are meant to override, such as deliver, clearly in the base class and document them.
  • If all you need is shared code, consider a helper function or composition before reaching for extends.

Mini challenge

Mini challenge: email and SMS notifications

Replace the copied code from the problem section with a Notification base class and two child classes. The empty-message check must be written once, in the base class.

  • Notification stores the recipient; send(message) returns "Not sent to <recipient>: empty message" for a blank message and otherwise calls this.deliver(message)
  • EmailNotification(recipient, subject) calls super(), stores the subject and overrides deliver()
  • SmsNotification writes no constructor and overrides only deliver(), cutting messages over 20 characters to 17 plus "..."
  • Put both notifications in one array and call send() on each in a single loop
notify.js
class Notification {
  constructor(recipient) {
    // TODO: store the recipient
  }

  send(message) {
    // TODO: refuse blank messages, otherwise return this.deliver(message)
  }

  deliver(message) {
    // TODO: a generic fallback delivery string
  }
}

class EmailNotification extends Notification {
  // TODO: constructor(recipient, subject) that calls super first
  // TODO: deliver(message) -> "Email to <recipient> [<subject>]: <message>"
}

class SmsNotification extends Notification {
  // TODO: deliver(message) -> "SMS to <recipient>: <message, shortened>"
}

// TODO: send "Your order has shipped today" through both, then a blank SMS

Expected: The console prints three lines: Email to su@example.com [Order]: Your order has shipped today SMS to +95 9 123 456: Your order has sh... Not sent to +95 9 123 456: empty message

Show hint

message.trim() is an empty, falsy string for blank input, so if (!message.trim()) catches it. Inside send(), this.deliver() finds the child's override because lookup starts at the object's own class.

Show solution
notify.js
class Notification {
  constructor(recipient) {
    this.recipient = recipient;
  }

  send(message) {
    if (!message.trim()) return `Not sent to ${this.recipient}: empty message`;
    return this.deliver(message);
  }

  deliver(message) {
    return `Sending "${message}" to ${this.recipient}`;
  }
}

class EmailNotification extends Notification {
  constructor(recipient, subject) {
    super(recipient);
    this.subject = subject;
  }

  deliver(message) {
    return `Email to ${this.recipient} [${this.subject}]: ${message}`;
  }
}

class SmsNotification extends Notification {
  deliver(message) {
    const short = message.length > 20 ? message.slice(0, 17) + "..." : message;
    return `SMS to ${this.recipient}: ${short}`;
  }
}

const notifications = [
  new EmailNotification("su@example.com", "Order"),
  new SmsNotification("+95 9 123 456"),
];
for (const n of notifications) {
  console.log(n.send("Your order has shipped today"));
}
console.log(notifications[1].send("   "));

Quick quiz 1 / 3

If Dog's constructor becomes { this.breed = breed; super(name); }, what does new Dog("Rex", "Pug") do?

Quick quiz 2 / 3

In the example, what happens when you call cat.fetch()?

Quick quiz 3 / 3

Which relationship below is the best fit for inheritance (extends)?

What to remember

  • class Child extends Parent links the prototype chains, so the child inherits the parent's methods.
  • A child constructor must call super() before using this; with no constructor you get a default one.
  • A same-named method overrides the parent's, and super.method() reuses the parent's behavior.
  • Use inheritance only for a real is-a relationship; choose composition for has-a.

MDN — Using Classes — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Inheritance | Thuta Learning