Advanced · 7 of 11 · 20 min read
Inheritance
The extends and super keywords, the pre-class pattern they replaced, and why composition is usually the better answer.
- Inheritance
Inheritance lets one class build on another: the subclass gets the parent’s methods and adds or
replaces what it needs. Underneath, extends is wiring up two prototype links.
extends
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
describe() {
return `I am ${this.name}`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // run Animal's constructor first
this.breed = breed; // now `this` exists
}
speak() {
return `${this.name} barks`; // override
}
fetch() {
return `${this.name} fetches`; // add
}
}
const rex = new Dog('Rex', 'Collie');
console.log(rex.speak()); // "Rex barks" — the override
console.log(rex.describe()); // "I am Rex" — inherited
console.log(rex.fetch()); // "Rex fetches" — added
console.log(rex.breed); // "Collie"
console.log(rex instanceof Dog, rex instanceof Animal); // true true
Two chains are created, which is what makes both instance methods and statics inherit:
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // instances
console.log(Object.getPrototypeOf(Dog) === Animal); // statics
rex → Dog.prototype → Animal.prototype → Object.prototype → null
A method call walks that chain and stops at the first match, which is exactly what “override” means.
super
Two jobs, depending on where it appears.
In a constructor, super(...) calls the parent constructor:
class Base {
constructor() { this.created = true; }
}
class Broken extends Base {
constructor() {
// this.x = 1; // ReferenceError: Must call super constructor before accessing 'this'
super();
this.x = 1; // fine
}
}
console.log(new Broken().created); // true
Omitting super() entirely in a subclass that has a constructor is also an error:
class AlsoBroken extends Base {
constructor() {
// ReferenceError on construction: super was never called
}
}
If you write no constructor, you get an implicit constructor(...args) { super(...args) }, which
is why most subclasses do not need one at all:
class Cat extends Animal {
speak() { return `${this.name} meows`; }
}
console.log(new Cat('Kitty').speak()); // "Kitty meows" — name was forwarded
In a method, super.method() calls the parent’s version — the way to extend rather than replace:
class Logger {
log(message) { return `[log] ${message}`; }
}
class TimestampLogger extends Logger {
log(message) {
return `[2026] ${super.log(message)}`; // reuse, then decorate
}
}
console.log(new TimestampLogger().log('hi')); // "[2026] [log] hi"
super in a static method reaches the parent’s static:
class A {
static create() { return 'A.create'; }
}
class B extends A {
static create() { return `B via ${super.create()}`; }
}
console.log(B.create()); // "B via A.create"
Fields and construction order
The order matters and explains a real class of bug: the parent constructor runs before the subclass’s fields are initialised.
class Parent {
constructor() {
this.setup(); // calls the override — on a half-built object
}
setup() { return 'parent setup'; }
}
class Child extends Parent {
value = 'ready'; // initialised after super() returns
setup() {
console.log('child setup sees:', this.value); // undefined
}
}
new Child(); // child setup sees: undefined
Calling an overridable method from a constructor is the mistake. Initialise, then let the caller invoke the method.
The pre-class pattern
Worth being able to read, since it is what extends compiles down to conceptually and it is all over
older code:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
return `${this.name} makes a sound`;
};
function Dog(name, breed) {
Animal.call(this, name); // 1. the `super()` equivalent
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype); // 2. link the prototypes
Dog.prototype.constructor = Dog; // 3. repair the back-reference
Dog.prototype.speak = function () {
return `${this.name} barks`;
};
const rex = new Dog('Rex', 'Collie');
console.log(rex.speak(), rex instanceof Animal); // "Rex barks" true
Step three is the one everybody forgot, which is why instance.constructor was unreliable in
pre-ES6 code. Note also that Dog.prototype = new Animal() — a common older variant — is wrong: it
runs the parent constructor once at definition time and puts its instance properties on the shared
prototype.
Animal.call(this) |
super() |
|
|---|---|---|
Creates this |
no — it already exists | yes |
| Required | by convention | by the language |
Can run after using this |
yes | no |
Repairs constructor |
you must | automatic |
Extending built-ins
extends works on Array, Error and the rest, which the pre-class pattern could not do properly:
class Stack extends Array {
peek() {
return this[this.length - 1];
}
}
const s = new Stack();
s.push(1, 2);
console.log(s.peek(), s.length, Array.isArray(s)); // 2 2 true
console.log(s.map((n) => n * 2) instanceof Stack); // true — methods preserve the subclass
A custom error class is the most useful case in practice:
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError'; // otherwise it reports as "Error"
this.field = field;
}
}
try {
throw new ValidationError('email', 'is required');
} catch (error) {
console.log(error instanceof ValidationError, error instanceof Error); // true true
console.log(error.name, error.field, error.message); // ValidationError email is required
}
Setting this.name is not optional if you want readable logs — Error uses the constructor’s own
name, not the subclass’s.
Abstract-ish base classes
JavaScript has no abstract, but new.target gets you most of the way:
class Shape {
constructor() {
if (new.target === Shape) throw new TypeError('Shape is abstract');
}
area() {
throw new Error('subclasses must implement area()');
}
}
class Square extends Shape {
constructor(side) { super(); this.side = side; }
area() { return this.side ** 2; }
}
console.log(new Square(3).area()); // 9
// new Shape(); // TypeError: Shape is abstract
Composition over inheritance
Inheritance is a permanent, single-parent commitment. Most of what people reach for it for is better served by composing behaviour.
The problem it creates, in a few lines:
class Bird extends Animal {
fly() { return `${this.name} flies`; }
}
class Penguin extends Bird {} // inherits fly() — and penguins do not fly
The hierarchy was wrong as soon as one subclass did not want a parent’s method. Composition has no such problem:
const canFly = (state) => ({ fly: () => `${state.name} flies` });
const canSwim = (state) => ({ swim: () => `${state.name} swims` });
const canEat = (state) => ({ eat: () => `${state.name} eats` });
function makeDuck(name) {
const state = { name };
return { ...state, ...canEat(state), ...canFly(state), ...canSwim(state) };
}
function makePenguin(name) {
const state = { name };
return { ...state, ...canEat(state), ...canSwim(state) }; // no fly, no awkwardness
}
console.log(makeDuck('Donald').fly()); // "Donald flies"
console.log(makePenguin('Pingu').swim()); // "Pingu swims"
// makePenguin('Pingu').fly; // undefined — correctly absent
Each ability is a small function, abilities combine freely, and nothing is inherited that is not wanted.
| Inheritance | Composition | |
|---|---|---|
| Relationship | is-a | has-a / can-do |
| Parents | one | any number of behaviours |
| Changing it later | touches every subclass | add or remove one object |
| Good for | a genuine, stable taxonomy | mixing capabilities |
Inheritance is still right when the relationship really is “is-a” and stable: a custom Error, a
framework component base class, a shape hierarchy. Use it two or three levels deep at most; beyond
that, nobody can tell where a method came from.
Common mistakes
Using this before super()
Mistake. Assigning a property at the top of a subclass constructor.
Why it fails. super() is what allocates the object; before it, this is not initialised.
What to do instead. Call super(...) first, always on the first line.
Forgetting this.name in a custom error
Mistake. class NotFound extends Error {} with no name set.
Why it fails. error.name comes from Error, so logs and messages say “Error” and the type is
invisible in production.
What to do instead. Set this.name = 'NotFound' in the constructor, or use
this.constructor.name.
Inheriting to share a few helpers
Mistake. A BaseService that every service extends, for three utility methods.
Why it fails. It couples unrelated classes, consumes the single parent slot, and grows until
nobody knows what is inherited.
What to do instead. Import the helpers as functions, or compose them in.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does class B extends A actually set up?
instanceof asks a question about the prototype chain, not about the constructor you called.
What does this log?
class A {}
class B extends A {}
const b = new B();
console.log(b instanceof A);What does "composition over inheritance" mean in practice?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.