Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 34

Inheritance with `extends` and `super()`

This lesson is built with resources from youtube.com, javascript.info and 1 more site.

Hello! Let's dive into the second lesson of our module on "Advanced OOP."

In our last session, we established a critical concept: the ES6 class syntax is "syntactic sugar" over JavaScript's fundamental prototype-based inheritance. We saw how class provides a cleaner, more readable structure compared to the manual, multi-step process of using constructor functions and Object.create.

Today, we'll build directly on that foundation. Our learning outcome is to implement class inheritance using extends and correctly call parent constructors with super(). While we touched on these keywords last time, this lesson is a deep dive into their mechanics, rules, and practical applications. We'll move from knowing what they are to knowing how and, crucially, why they work the way they do.

The extends Keyword: Setting Up the Chain

The extends keyword is the cornerstone of class inheritance in JavaScript. It creates a subclass (or "child class") that inherits from a superclass (or "parent class").

// Parent class
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

// Child class
class SoftwareEngineer extends Person {
  // For now, this class adds no new functionality.
  // It inherits everything from Person.
}

const ada = new SoftwareEngineer('Ada Lovelace');
ada.introduce(); // Output: Hello, my name is Ada Lovelace.

As we learned previously, extends handles the boilerplate of setting up the prototype chain for you. What it does under the hood is conceptually equivalent to setting the child's prototype to inherit from the parent's prototype.

Class inheritance

The article 'Class inheritance' on javascript.info provides an excellent technical summary of what the extends keyword accomplishes behind the scenes. This will connect the syntax directly to the prototype mechanics we reviewed in the last lesson.

Read the first part of this article, up to the section 'Overriding a method'. Focus on the explanation of how extends sets Rabbit.prototype.[[Prototype]] to Animal.prototype and how the engine looks up methods on the chain.


The Derived Constructor: Rules and super()

The example above is simple because our SoftwareEngineer class didn't have its own constructor. When a child class lacks a constructor, JavaScript provides an empty one that simply calls the parent constructor, like so:

constructor(...args) {
  super(...args);
}

But what happens when the child class needs to initialize its own properties? This is where a strict rule comes into play.

Let's try to add a programmingLanguage property to our SoftwareEngineer class.

class SoftwareEngineer extends Person {
  constructor(name, programmingLanguage) {
    // A common mistake: trying to use 'this' before calling super()
    this.programmingLanguage = programmingLanguage; // This will cause an error!
    super(name); 
  }

  code() {
    console.log(`${this.name} is writing code in ${this.programmingLanguage}.`);
  }
}

Running this code will result in a ReferenceError: Must call super constructor in derived class before accessing 'this'.

This error is not arbitrary; it's fundamental to how new works with inheritance.

  • When you new a base class (Person), an empty object is created and assigned to this.
  • When you new a derived class (SoftwareEngineer), it does not create the this object. It delegates that responsibility to the parent class constructor.

Therefore, you must call super() to execute the parent constructor first. The parent constructor creates and initializes the object referenced by this, which you can then modify in the child constructor.

The JavaScript SUPER keyword is super! 🦸‍♂️

This video from Bro Code provides a very clear, practical demonstration of this rule. It walks through setting up parent and child classes, shows the exact error you get when forgetting super(), and then shows how to fix it.

Watch the sections that set up the classes (0:24-1:41), demonstrate the error (2:32-3:20), and then show how to pass arguments to the parent constructor to avoid repeating code (3:20-5:59).

To truly understand why this rule exists, we need to look at an internal detail of the JavaScript engine.

Class inheritance

For the deep dive, let's return to the 'Class inheritance' article. It explains the concept of a 'derived constructor' and its special internal property that enforces the super()-before-this rule.

Read the section 'Overriding constructor'. It provides the definitive explanation for why a derived constructor must call super() to create this. This is the core theoretical takeaway of today's lesson.

The correct implementation of our SoftwareEngineer class constructor looks like this:

class SoftwareEngineer extends Person {
  constructor(name, programmingLanguage) {
    // Correct: Call the parent constructor FIRST to initialize 'this' and set 'name'.
    super(name);
    
    // NOW we can use 'this' to add child-specific properties.
    this.programmingLanguage = programmingLanguage;
  }

  code() {
    console.log(`${this.name} is writing code in ${this.programmingLanguage}.`);
  }
}

const bjarne = new SoftwareEngineer('Bjarne Stroustrup', 'C++');
bjarne.introduce(); // "Hello, my name is Bjarne Stroustrup."
bjarne.code();      // "Bjarne Stroustrup is writing code in C++."
Test your understanding!

The following code has an error that prevents Rabbit objects from being created. Can you identify the mistake and fix it?

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

class Rabbit extends Animal {
  constructor(name) {
    this.created = Date.now(); // Hint: When can you use 'this'?
    this.name = name;
  }
}

let rabbit = new Rabbit("White Rabbit");
console.log(rabbit.name);
Show answer

The error is ReferenceError: Must call super constructor in derived class before accessing 'this'. The Rabbit constructor attempts to assign to this.created before the this object has been created by the parent Animal constructor.

The fix is to call super(name) at the beginning of the Rabbit constructor. This both creates this and handles the assignment of the name property, making the subsequent this.name = name line redundant.

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

class Rabbit extends Animal {
  constructor(name) {
    // Call the parent constructor first!
    super(name); 
    // Now you can add properties specific to the Rabbit class.
    this.created = Date.now();
  }
}

let rabbit = new Rabbit("White Rabbit"); // Works now!
console.log(`${rabbit.name} was created at ${rabbit.created}.`);

This is the same problem presented in the "Error creating an instance" task from the javascript.info article.


Overriding Methods with super.method()

Inheritance isn't just about reusing code; it's also about specializing it. A child class can provide its own version of a method that it inherited from the parent. This is called method overriding.

However, you often don't want to completely replace the parent's method. Instead, you might want to add to it. The super keyword can be used here as well: super.methodName() allows you to call the parent's version of a method from within the child's overridden method.

The JavaScript SUPER keyword is super! 🦸‍♂️

The Bro Code video also has an excellent segment demonstrating how to override a method and call the parent's implementation.

Watch from 5:59 to 9:00. This section shows how the run, swim, and fly methods in the child classes extend the functionality of the parent's move method by calling super.move().

Let's apply this to our SoftwareEngineer class. We can override the introduce() method to provide a more specific introduction, while still reusing the base introduction from the Person class.

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    return `Hello, my name is ${this.name}.`;
  }
}

class SoftwareEngineer extends Person {
  constructor(name, programmingLanguage) {
    super(name);
    this.programmingLanguage = programmingLanguage;
  }

  // Overriding the introduce method
  introduce() {
    // Call the parent's introduce() method to get the base string
    const baseIntroduction = super.introduce(); 
    
    // Add specialized information
    console.log(`${baseIntroduction} I am a software engineer specializing in ${this.programmingLanguage}.`);
  }
}

const grace = new SoftwareEngineer('Grace Hopper', 'COBOL');
grace.introduce();
// Output: Hello, my name is Grace Hopper. I am a software engineer specializing in COBOL.

Conclusion

Today, we took a detailed look at the mechanics of class inheritance in JavaScript. You now have the tools to create robust class hierarchies, correctly managing initialization and method specialization.

Key Takeaways:

  • The extends keyword establishes a prototype-based inheritance chain between a child and parent class.
  • A constructor in a derived (child) class must call super() before it can use the this keyword.
  • super() invokes the parent class's constructor, which is responsible for creating the this object. Arguments can be passed via super(arg1, arg2) to the parent.
  • super.methodName() can be used within an overridden child method to call the parent's implementation, allowing you to extend functionality rather than completely replacing it.

Next Up

So far, all the properties and methods we've defined (name, introduce, code) belong to instances of a class. You have to create an object with new to use them. But what about properties or utility methods that should belong to the class itself, rather than any single instance? In our next lesson, we will explore this by learning how to define static methods and properties.