Class Inheritance

Updated · 8 min read
hardES2026javascriptclassesinheritanceextendssuper

Inheritance lets one class build on another: a subclass (or child class) gets all the fields and methods of its superclass (parent class) and can add its own or change inherited behavior. In JavaScript, class Child extends Parent sets this up, and super calls the parent's constructor and methods. Underneath, it links two prototype chains. Inheritance is useful for true "is a kind of" relationships, but it is easy to overuse; this lesson also shows composition, which is often the better choice.

In One Minute

  • class CardPayment extends Payment { ... } creates a subclass.
  • In a subclass constructor, call super(...args) before using this.
  • Methods with the same name override the parent's; call the parent's version with super.method().
  • instanceof is true for the class and every ancestor.
  • You can extend built-ins like Error, Array and Map.
  • Prefer composition (objects that contain helpers) when the relationship isn't truly "is a".

extends and super

Syntax

syntax.js
class Child extends Parent {
  constructor(a, b, extra) {
    super(a, b);          // runs Parent's constructor: required before using this
    this.extra = extra;
  }
  method() {
    const base = super.method();   // Parent's version
    return base + " plus more";
  }
}

Example

extends.js▶ Try it
class Payment {
  constructor(name, amount) {
    this.name = name;
    this.amount = amount;
  }
  fee() {
    return 0;
  }
  receipt() {
    return `${this.name}: $${this.amount} (fee $${this.fee()})`;
  }
}
 
class CardPayment extends Payment {
  constructor(name, amount, last4) {
    super(name, amount);
    this.last4 = last4;
  }
  fee() {
    return Math.round(this.amount * 0.029 * 100) / 100;
  }
  receipt() {
    return `${super.receipt()} card ending ${this.last4}`;
  }
}
 
const check = new Payment("Navika", 120);
const card = new CardPayment("Srihitha", 85, "4242");
console.log(check.receipt());
console.log(card.receipt());
console.log(card instanceof CardPayment, card instanceof Payment);
Output
Navika: $120 (fee $0)
Srihitha: $85 (fee $2.47) card ending 4242
true true

Explanation: CardPayment inherits name, amount and receipt from Payment. It overrides fee with card-processing logic. Its own receipt calls super.receipt() to reuse the parent's text and add to it. Notice that the parent's receipt calls this.fee(), and for a card payment that runs the child's fee: methods are looked up on the actual object, so overrides take effect even inside inherited code.

The Subclass Constructor

A subclass constructor must call super() before touching this, because the parent is responsible for creating and initializing the object:

super-first.js▶ Try it
class Base {
  constructor() { this.createdAt = "2026-01-05"; }
}
 
class Broken extends Base {
  constructor() {
    this.name = "too early";
    super();
  }
}
 
try {
  new Broken();
} catch (err) {
  console.log(err.name + ": " + err.message);
}
 
class Fine extends Base {}
console.log(new Fine().createdAt);
Output
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
2026-01-05

If a subclass has no constructor, JavaScript supplies one that passes every argument along: constructor(...args) { super(...args); }. Subclass fields are initialized right after super() returns.

How It Works: Two Prototype Chains

extends links both the instances' chain and the classes' chain:

chains.js▶ Try it
class Payment {
  static kind() { return "payment"; }
}
class CardPayment extends Payment {}
 
const card = new CardPayment();
console.log(Object.getPrototypeOf(card) === CardPayment.prototype);
console.log(Object.getPrototypeOf(CardPayment.prototype) === Payment.prototype);
console.log(Object.getPrototypeOf(CardPayment) === Payment);
console.log(CardPayment.kind());
Output
true
true
true
payment
What extends sets up
card ──▶ CardPayment.prototype ──▶ Payment.prototype ──▶ Object.prototype ──▶ null
CardPayment ──▶ Payment ──▶ Function.prototype ──▶ Object.prototype ──▶ null

The first chain lets instances find inherited methods. The second lets static methods be inherited too: CardPayment.kind() finds Payment.kind.

Overriding and super

ExpressionMeans
super(...)Call the parent constructor (only in a constructor)
super.method(...)Call the parent's version of a method, with the current this
super.propRead a property from the parent's prototype

Overriding replaces behavior; calling super.method() inside the override extends it instead. A good rule: an override should keep the parent's promises (same kind of arguments, same kind of result), so code written for the parent works with any child. This is called the Liskov substitution principle.

Extending Built-In Classes

Built-in classes such as Error, Array and Map can be extended. Custom errors are the most common case (see the error objects lesson):

builtins.js▶ Try it
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}
 
class PaymentList extends Array {
  total() {
    return this.reduce((sum, p) => sum + p.amount, 0);
  }
}
 
const err = new ValidationError("amount", "Amount must be positive");
console.log(err instanceof Error, err.name, err.field);
 
const list = PaymentList.from([{ amount: 120 }, { amount: 85 }]);
console.log(list.total(), list.length);
const big = list.filter((p) => p.amount > 100);
console.log(big instanceof PaymentList, big.total());
Output
true ValidationError amount
205 2
true 120

Array methods like filter and map on a subclass return instances of the subclass, so big.total() still works. (This behavior, through Symbol.species, has caused enough performance and security trouble that extending Array is generally discouraged; a class that contains an array is simpler.)

Composition Over Inheritance

Inheritance creates a tight link: a change in the parent affects every child, and a class can only extend one parent. When the relationship is "has a" or "uses a" rather than "is a", build the object from parts instead:

composition.js▶ Try it
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
 
class ReminderSender {
  send(student) { return `Email to ${student.name}: ${usd.format(student.balance)} due`; }
}
 
class LateFeePolicy {
  constructor(rate, cap) { this.rate = rate; this.cap = cap; }
  feeFor(daysLate) { return Math.min(daysLate * this.rate, this.cap); }
}
 
class FeeTracker {
  constructor({ sender, policy }) {
    this.sender = sender;
    this.policy = policy;
  }
  process(student) {
    const fee = this.policy.feeFor(student.daysLate);
    return this.sender.send({ ...student, balance: student.balance + fee });
  }
}
 
const tracker = new FeeTracker({ sender: new ReminderSender(), policy: new LateFeePolicy(2, 30) });
console.log(tracker.process({ name: "Advitha", balance: 45, daysLate: 20 }));
Output
Email to Advitha: $75.00 due

With composition, FeeTracker doesn't care how reminders are sent or how fees are computed; swap in an SmsSender or a different policy without touching it, and test each part on its own.

In Practice

The Fee Tracker models payment types with one base class and small subclasses that override only what differs:

payment-types.js▶ Try it
class Payment {
  constructor(name, amount) {
    this.name = name;
    this.amount = amount;
  }
  get processingFee() { return 0; }
  get net() { return Math.round((this.amount - this.processingFee) * 100) / 100; }
  toString() { return `${this.constructor.name} ${this.name}: $${this.amount} (net $${this.net})`; }
}
 
class CardPayment extends Payment {
  get processingFee() { return Math.round((this.amount * 0.029 + 0.3) * 100) / 100; }
}
 
class AchPayment extends Payment {
  get processingFee() { return Math.min(this.amount * 0.008, 5); }
}
 
const payments = [new Payment("Navika", 120), new CardPayment("Srihitha", 85), new AchPayment("Advitha", 450)];
for (const p of payments) console.log(String(p));
console.log("Total net:", payments.reduce((sum, p) => sum + p.net, 0));
Output
Payment Navika: $120 (net $120)
CardPayment Srihitha: $85 (net $82.23)
AchPayment Advitha: $450 (net $446.4)
Total net: 648.63

this.constructor.name reads the actual class name of each object, so the shared toString describes every type correctly. The loop treats all payments the same way while each computes its own fee: this is polymorphism.

Common Mistakes

Using this before super(). ReferenceError. Call super first.

Forgetting super.method() when extending behavior. The parent's logic is silently skipped.

Deep inheritance chains. Changes ripple everywhere. Prefer composition.

Extending a class just to reuse one helper. Import or compose the helper instead.

Practice

Challenge: Create a LatePayment class that extends Payment (with name and amount), takes daysLate, and overrides total() so it adds $2 per day late (capped at $30) to the parent's total().

Show solution
late-payment.js▶ Try it
class Payment {
  constructor(name, amount) {
    this.name = name;
    this.amount = amount;
  }
  total() {
    return this.amount;
  }
}
 
class LatePayment extends Payment {
  constructor(name, amount, daysLate) {
    super(name, amount);
    this.daysLate = daysLate;
  }
  total() {
    return super.total() + Math.min(this.daysLate * 2, 30);
  }
}
 
console.log(new Payment("Navika", 120).total());
console.log(new LatePayment("Advitha", 45, 6).total());
console.log(new LatePayment("Srihitha", 85, 40).total());
Output
120
57
115

Quick check: Class inheritance

3 questions
1What must a subclass constructor do before using this?
2A parent method calls this.fee(), and the child overrides fee. Which runs for a child instance?
3When is composition better than inheritance?

Key Takeaways

TaskCode
Subclassclass CardPayment extends Payment {}
Parent constructorsuper(name, amount)
Parent methodsuper.receipt()
Check the typeobj instanceof Payment
Actual class namethis.constructor.name

Was this tutorial helpful?

Lesson 98 of 139