JavaScript Interview Question #110

How does inheritance work with extends and super?

Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate

Quick Interview Answer

The extends keyword creates a derived class whose instances inherit behavior from the base class. In a derived constructor, super must be called before accessing this because it initializes the base portion of the instance.

Detailed Explanation

The extends keyword creates a derived class whose instances inherit behavior from the base class. In a derived constructor, super must be called before accessing this because it initializes the base portion of the instance.

super can also be used to call base-class methods. JavaScript class inheritance ultimately operates through prototype-chain relationships.

Code Example

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

    describe() {
        return this.name;
    }
}

class Developer extends Person {
    constructor(name, language) {
        super(name);
        this.language = language;
    }

    describe() {
        return `${super.describe()} - ${this.language}`;
    }
}