← Back to JavaScript, page 9

javascript-0178 · Medium mid

How do extends, super, and new.target work in class inheritance, and what are the common traps?

extends links both the prototype chain of instances and the constructor chain of the classes. A derived constructor must call super() before it touches this, because the parent constructor creates the object. super.method() calls the parent version using the home object, and new.target tells a constructor which class was called with new, which is how abstract classes are written. Extending built-ins works and keeps their special behavior.

Full answer

class B extends A sets two links: B.prototype.__proto__ === A.prototype for instance methods, and B.__proto__ === A so that static members are inherited too.

Construction rules:

  • In a base class, new creates the object and the constructor initializes it. In a derived class the object is created by the parent constructor, so you must call super(...) before reading or writing this, otherwise you get a ReferenceError. If a derived class has no constructor, the default one passes all arguments to super.
  • A constructor may return an object, which replaces this. Returning a primitive is ignored, and a derived constructor that returns a primitive other than undefined throws.
  • Class fields of the derived class are initialized right after super() returns, so a parent constructor that calls an overridden method will see the derived fields as undefined. Do not call overridable methods from constructors.
  • super.method() looks up the method on the parent prototype but calls it with the current this. It works in object literal methods too, because it uses the method's home object, but not in plain functions or arrow functions that are not inside a method.
  • new.target is the constructor that was invoked with new, and is undefined in a normal call. In a parent constructor it is the derived class, so if (new.target === Shape) throw ... makes an abstract class, and a factory can pick behavior by new.target.name.
  • extends null creates a class whose instances have no Object.prototype, and it cannot be constructed without a custom return.
  • Extending built-ins works: class Stack extends Array. Methods such as map and filter create the result through Symbol.species, so they return a Stack. Override static get [Symbol.species]() { return Array; } to return a plain array. class MyError extends Error needs super(message) and sets name explicitly.
  • instanceof checks the prototype chain, and a method defined on the parent is found by lookup at call time, so changing the parent prototype later affects all children.

Alternative to remember: deep hierarchies are hard to change. Prefer composition for sharing behavior, and use inheritance for real is-a relationships with a stable parent.

javascript
class Shape {
  constructor(name) {
    if (new.target === Shape) throw new TypeError('Shape is abstract');
    this.name = name;
    console.log(`  Shape constructor, new.target is ${new.target.name}, describe() gives: ${this.describe()}`);
  }
  area() {
    throw new Error(`${this.constructor.name} must implement area`);
  }
  describe() {
    return `${this.name} with area ${this.area().toFixed(2)}`;
  }
  static create(...args) {
    return new this(...args);
  }
}

class Circle extends Shape {
  radius = 1;
  constructor(radius) {
    super('circle');
    this.radius = radius;
  }
  area() {
    return Math.PI * (this.radius ?? 0) ** 2;
  }
  describe() {
    return 'round ' + super.describe();
  }
}

console.log('abstract:', (() => { try { return new Shape('x'); } catch (e) { return e.message; } })());
const circle = Circle.create(2);
console.log(circle.describe());
console.log('prototype links:', Object.getPrototypeOf(Circle) === Shape, Object.getPrototypeOf(Circle.prototype) === Shape.prototype);

class Broken extends Shape {
  constructor() {
    this.x = 1;
    super('broken');
  }
}
try { new Broken(); } catch (e) { console.log('this before super:', e.name); }

class Returns extends Shape {
  constructor() {
    super('returns');
    return { replaced: true };
  }
  area() { return 1; }
}
console.log('constructor returning an object:', new Returns());

class Stack extends Array {
  peek() { return this[this.length - 1]; }
}
const stack = Stack.from([1, 2, 3]);
console.log('map keeps the subclass:', stack.map((n) => n * 2) instanceof Stack, stack.peek(), stack.length);
class PlainStack extends Array {
  static get [Symbol.species]() { return Array; }
}
console.log('species override:', PlainStack.from([1]).map((n) => n) instanceof PlainStack);

const base = { hello() { return 'base hello'; } };
const child = { __proto__: base, hello() { return 'child then ' + super.hello(); } };
console.log(child.hello());

function plain() { return new.target === undefined ? 'called without new' : 'called with new'; }
console.log(plain(), '|', new plain() instanceof plain);

Run with Node.js v24.22.1 as js-178.js; two runs gave identical output. Output: abstract: Shape is abstract Shape constructor, new.target is Circle, describe() gives: round circle with area 0.00 round circle with area 12.57 prototype links: true true this before super: ReferenceError Shape constructor, new.target is Returns, describe() gives: returns with area 1.00 constructor returning an object: { replaced: true } map keeps the subclass: true 3 3 species override: false child then base hello called without new | true

Key points

  • extends links instance prototypes and class constructors, so static members are inherited.
  • Call super() before using this in a derived constructor; field initializers run right after it.
  • super.method() uses the home object but the current this.
  • new.target names the class called with new; use it for abstract classes.
  • Built-in subclasses work, and Symbol.species controls the type of derived results.

Common mistakes

  • Using this before super() in a derived constructor.
  • Calling overridable methods from a base constructor and reading uninitialized derived fields.
  • Forgetting that arrow functions and plain functions cannot use super.
  • Building deep hierarchies where composition would be simpler.

Follow-ups

  • What does Symbol.species do and when would you override it?
  • How would you implement an abstract method check?
  • How do static methods get inherited?

Tips

  • Describe the two prototype links, instance and static.
  • Explain why super() comes first: the parent creates the object.
  • Mention the constructor-calls-override trap.