Class Inheritance
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 usingthis. - Methods with the same name override the parent's; call the parent's version with
super.method(). instanceofis true for the class and every ancestor.- You can extend built-ins like
Error,ArrayandMap. - Prefer composition (objects that contain helpers) when the relationship isn't truly "is a".
extends and super
Syntax
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
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);Navika: $120 (fee $0)
Srihitha: $85 (fee $2.47) card ending 4242
true trueExplanation: 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:
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);ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
2026-01-05If 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:
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());true
true
true
paymentcard ──▶ CardPayment.prototype ──▶ Payment.prototype ──▶ Object.prototype ──▶ null
CardPayment ──▶ Payment ──▶ Function.prototype ──▶ Object.prototype ──▶ nullThe first chain lets instances find inherited methods. The second lets static methods be inherited too: CardPayment.kind() finds Payment.kind.
Overriding and super
| Expression | Means |
|---|---|
super(...) | Call the parent constructor (only in a constructor) |
super.method(...) | Call the parent's version of a method, with the current this |
super.prop | Read 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):
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());true ValidationError amount
205 2
true 120Array 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:
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 }));class FeeTracker { /* ... */ }
class FeeTrackerWithEmail extends FeeTracker { /* adds sending */ }
class FeeTrackerWithEmailAndStrictFees extends FeeTrackerWithEmail { /* changes fees */ }
// Every new combination needs another subclass.Email to Advitha: $75.00 dueWith 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:
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));Payment Navika: $120 (net $120)
CardPayment Srihitha: $85 (net $82.23)
AchPayment Advitha: $450 (net $446.4)
Total net: 648.63this.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
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());120
57
115Key Takeaways
| Task | Code |
|---|---|
| Subclass | class CardPayment extends Payment {} |
| Parent constructor | super(name, amount) |
| Parent method | super.receipt() |
| Check the type | obj instanceof Payment |
| Actual class name | this.constructor.name |
Was this tutorial helpful?