Inheritance

Topic 3 of 4 in Classes & prototypes5 min readBeginnerFree course

Overview

extends creates a class that starts with everything another class has, then adds or changes things. The original is called the parent (or superclass, base class); the new one is the child (or subclass).

JavaScript
class User {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hi, ${this.name}`;
  }
}

class Teacher extends User {
  constructor(name, subject) {
    super(name);           // run User's constructor first
    this.subject = subject;
  }
  greet() {
    return `${super.greet()}! I teach ${this.subject}.`;
  }
}

new Teacher('Meera', 'JavaScript').greet();
// 'Hi, Meera! I teach JavaScript.'

Inheritance lets you put shared behaviour in one place: every kind of user gets greet (and anything else in User) without copying it.

How it works

extends simply links prototypes together. A teacher’s prototype is Teacher.prototype, whose prototype is User.prototype. Method lookups walk up that chain and use the first match they find.

class Teacher extends class User. The instance meera holds name and subject; its chain goes Teacher.prototype (with an overriding greet), then User.prototype (with the original greet), then Object.prototype. meera.greet() is found first on Teacher.prototype. meera is an instance of both Teacher and User.

super

  • In the constructor, super(...) calls the parent constructor. You must call it before touching this.
  • In a method, super.method() calls the parent’s version — handy when you want to extend behaviour rather than replace it.

Forgetting super in a child constructor is a common error:

JavaScript
class Admin extends User {
  constructor(name) {
    this.level = 'full'; // ReferenceError: Must call super constructor before accessing 'this'
  }
}

If the child doesn’t need a constructor of its own, leave it out — JavaScript automatically passes all arguments to the parent:

JavaScript
class Student extends User {
  enrol(course) {
    return `${this.name} enrolled in ${course}`;
  }
}

new Student('Ravi').enrol('SQL'); // 'Ravi enrolled in SQL'

Overriding methods

Defining a method with the same name as the parent’s overrides it for the child’s instances. You can:

  • replace the behaviour completely — just don’t call super;
  • extend it — call super.method() and add to the result, as Teacher.greet does.

The parent class is unaffected: plain users still get the original greet.

Polymorphism

Because every subclass has a greet method, code can call greet on a mixed list without knowing which kind each item is:

JavaScript
const people = [new User('Asha'), new Teacher('Meera', 'JS'), new Student('Ravi')];
for (const p of people) {
  console.log(p.greet()); // each uses its own version
}

This idea — many types, one interface — is called polymorphism.

Checking the family

JavaScript
const t = new Teacher('Meera', 'JS');
t instanceof Teacher; // true
t instanceof User;    // true
t instanceof Student; // false
t.constructor.name;   // 'Teacher'

Extending built-in classes

You can extend JavaScript’s own classes. This is very common with Error (see Custom errors):

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

Composition over inheritance

Deep class trees get hard to change. If Teacher extends User, and HeadTeacher extends Teacher, and OnlineHeadTeacher extends HeadTeacher… a change at the top ripples everywhere, and some combinations don’t fit the tree at all (what about an online student?).

Often it’s simpler to give an object the pieces it needs:

JavaScript
const canLog = (obj) => ({ ...obj, log: () => console.log(obj.name) });

Or to have an object contain helpers rather than be one:

JavaScript
class Course {
  constructor(title, storage) {
    this.title = title;
    this.storage = storage; // has-a storage, rather than is-a storage
  }
  save() {
    this.storage.save(this.title);
  }
}

A good test: use extends only when “a Teacher is a User” is true in every situation. If it’s really “has a” or “can do”, use composition.

Keep hierarchies shallow — one or two levels is plenty for most programs.

Exercise

Extend a class

Create VideoLesson that extends Lesson, adds a duration field, and overrides summary() to include it, reusing the parent’s version with super.

JavaScript
class Lesson {
  constructor(title) {
    this.title = title;
  }
  summary() {
    return this.title;
  }
}

// write VideoLesson here

new VideoLesson('Closures', 12).summary(); // 'Closures (12 min video)'

Summary

  • extends makes a class inherit another class’s methods and fields.
  • Call super(...) in the constructor before using this.
  • Override a method by defining it again; call the parent’s with super.method().
  • An instance is instanceof its own class and every ancestor.
  • Prefer small hierarchies; composition is often simpler.