Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 156 ยท Classes and Objects in Depth

Inheritance with extends and super

Learn JavaScript class inheritance - create subclasses with extends, call parent constructors and methods with super, override methods and use instanceof.

Sometimes one kind of object is a more specific version of another. A savings account is a bank account that also earns interest. A video is a media item that also has a duration. Instead of copying the shared code into each class, you can let one class inherit from another and add or change only what is different.

JavaScript does this with two keywords: extends creates a subclass (also called a child or derived class) from a parent class (also called a base or superclass), and super lets the subclass call into the parent. In this lesson you will build small class hierarchies, override methods, use instanceof, and learn the rules that make super work, along with a few traps worth knowing early.

Creating a subclass with extends

Write class Child extends Parent. Instances of the child get every method of the parent automatically, plus anything the child defines itself:

JS A first subclass

Press Run (or Ctrl + Enter) to see the console output here.

No output.

SavingsAccount has no constructor of its own, so JavaScript gives it a default one that passes all arguments straight to the parent's constructor. That is why new SavingsAccount("Priya", 1000) still sets owner and balance.

How it works: two prototype chains

extends links the prototypes together, so the lookup you learned in Prototypes simply goes one step further:

TEXT
savings โ”€โ”€โ–บ SavingsAccount.prototype โ”€โ”€โ–บ Account.prototype โ”€โ”€โ–บ Object.prototype โ”€โ”€โ–บ null
              (addInterest)                (deposit, describe)

When you call savings.deposit(), JavaScript doesn't find deposit on savings or on SavingsAccount.prototype, so it keeps walking and finds it on Account.prototype. Nothing is copied; the subclass just adds one more link to the chain.

Constructors and super()

When a subclass needs extra data, it defines its own constructor. Inside it, you must call super(...) before you use this. super(...) runs the parent's constructor, which is what actually creates and sets up the object:

JS Subclass constructors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The rule exists because, in a subclass, the object doesn't exist yet until the parent constructor has run. Touching this before that throws a ReferenceError. Forgetting super() entirely throws too, as soon as the constructor finishes.

Class fields declared in a subclass are created right after super() returns, before the rest of the child constructor runs.

Overriding methods

A subclass can define a method with the same name as one in the parent. Because lookup finds the child's version first, it overrides the parent's. Inside the override, super.methodName() calls the parent's version, so you can extend behavior instead of rewriting it:

JS Overriding and super.method()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The loop at the end calls describe() without knowing or caring which kind of item it has. Each object answers in its own way. This is called polymorphism: one interface, many implementations. It is the main payoff of inheritance, because code that works with MediaItem automatically works with every subclass.

super.something works in any method, not just in overrides of the same name. You can also use it in getters, setters and static methods.

Checking types with instanceof

obj instanceof Class returns true if Class.prototype appears anywhere in obj's prototype chain. So an instance of a subclass is also an instance of every parent:

JS instanceof with a hierarchy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

instanceof is handy in error handling (if (error instanceof TypeError)), but checking types everywhere is often a sign that a method override would be cleaner. Instead of if (item instanceof Video) { ... } else if (item instanceof Podcast) { ... }, give each class its own method and just call it.

Static members are inherited too

extends links the classes themselves, not only their prototypes. A static method defined on the parent can be called on the child, and inside it this refers to the class it was called on:

JavaScript
class Model {
  static create(data) {
    return Object.assign(new this(), data); // `this` is the class
  }
}
class User extends Model {}

const u = User.create({ name: "Kai" });
u instanceof User; // true

You will learn more about static in Private Fields and Static Members.

Extending built-in classes

You can extend built-in classes such as Error, Array and Map. The most common, and most useful, case is custom errors:

JavaScript
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

Now error instanceof ValidationError lets you handle that kind of failure separately. Throwing and Custom Errors builds on this pattern.

Designing a good parent class

A parent class is a promise to every subclass, so it pays to design it carefully:

  • Put only what every child needs in the parent. If one subclass would have to override a method just to make it do nothing, that method probably doesn't belong in the parent.
  • Keep the parent's constructor small. Store the arguments and set up state. Leave work that depends on the subclass to methods called later.
  • Document what may be overridden. A short comment such as "subclasses provide area()" tells future readers which methods form the extension points.
  • Make a base class that must not be used directly throw. Check new.target, which holds the class that new was called with: if (new.target === Shape) throw new TypeError("Shape is abstract"). Subclasses pass the check because new.target is the subclass.

Traps to avoid

  • Calling overridable methods from a parent constructor. The parent constructor runs before the child's fields and constructor body. If it calls a method the child overrides, that override runs on a half-built object, and child fields are still undefined. Keep constructors simple and avoid calling overridable methods from them.
  • Deep hierarchies. Animal โ†’ Mammal โ†’ Dog โ†’ ServiceDog โ†’ GuideDog looks tidy at first, but every change to a parent ripples into every descendant, and real things rarely fit a single tree. One or two levels is usually plenty.
  • Inheriting just to reuse code. Use extends only when the child truly is a kind of parent and could be used anywhere the parent is expected. If you only want to borrow some behavior, composition is usually a better fit.

A class can extend only one parent. JavaScript has no multiple inheritance, which is another reason composition patterns exist.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In class Video extends MediaItem, what must the Video constructor do before using this?

    In a subclass, the object is created by the parent constructor. You must call super(...) first; using this before that throws a ReferenceError.
  2. 2. A subclass defines describe(), and so does its parent. How does the subclass call the parent's version from inside its own?

    super.describe() runs the parent's method with the same this. this.describe() would call the override again, forever.
  3. 3. class B extends A {} and class C extends B {}. For const c = new C(), which is true?

    instanceof checks the whole prototype chain, and A.prototype is in it, two links up.
  4. 4. What is polymorphism?

    Code like item.describe() works for every subclass, and each one supplies its own implementation through overriding.

Summary

  • class Child extends Parent makes instances of Child inherit everything from Parent by linking prototype chains.
  • A subclass constructor must call super(...) before using this; without a constructor, a default one forwards all arguments.
  • Define a method with the same name to override it; use super.method() to build on the parent's version.
  • Polymorphism lets one piece of code work with many subclasses.
  • instanceof checks the entire prototype chain; static methods are inherited too.
  • You can extend built-ins such as Error; keep hierarchies shallow and avoid calling overridable methods in constructors.

Next: Private Fields and Static Members โ€” truly private state and class-level properties.