0Pricing
JavaScript Academy · Lesson

Inheritance, super, and when to prefer composition

Extend a base class with extends, call super in constructors, override methods safely, and know when simple composition is better.

Big picture

Goal: Use basic inheritance without confusion.

  • extends makes a child class
  • super(...) calls the parent constructor
  • Override a method; optionally call super.method()
  • If it is not an “is-a”, prefer composition
Inheritance, super, and when to prefer composition — illustration 1

extends + super

Create a child with extends; call super(name) to run the parent constructor and set up this.

// Base class with a small field and method
class Animal {
  constructor(name) {
    this.name = name;
  }
  info() {
    return "Animal:" + this.name;
  }
}

// Child class extends the base and calls super(...)
class Dog extends Animal {
  constructor(name, breed) {
    // must call super() before using this
    super(name);
    this.breed = breed;
  }
  speak() {
    return "woof";
  }
}

const d = new Dog("Milo", "Beagle");
console.log(d.info(), d.speak());
Inheritance, super, and when to prefer composition — illustration 2

All lessons in this course

  1. Class fields, private # fields, static members
  2. Inheritance, super, and when to prefer composition
  3. Mixins (taste) — simple reuse without deep hierarchies
← Back to JavaScript Academy