Composition over Inheritance in JavaScript: Delegation, Mixins and Abstract Classes
When to extend a class and when not to: the problems with inheritance, composition and delegation with private helpers, strategy objects, Object.assign and subclass-factory mixins, abstract classes with template methods, duck-typed interfaces, and a checklist for designing class hierarchies.
kvi5hnuCode Sprout team member8 min readOn this page
extends makes inheritance easy, which makes it easy to overuse. Experienced developers follow a long-standing guideline: favor composition over inheritance. This article shows why, what composition looks like in JavaScript, how mixins share behavior across unrelated classes, and when a class hierarchy with abstract base classes really is the right design.
When inheritance goes wrong
Suppose you want a Tally that counts how many times each word appears. It maps words to counts, so extending Map seems natural:
class Tally extends Map {
add(word) {
return this.set(word, (this.get(word) ?? 0) + 1);
}
count(word) {
return this.get(word) ?? 0;
}
}
const tally = new Tally();
tally.add("cat").add("cat").add("dog");
console.log(tally.count("cat"));
tally.set("dog", "lots"); // inherited and unchecked
tally.set("bird", -3);
console.log(tally.count("dog"), tally.count("bird"));
2
lots -3
A Tally is a Map, so it inherits every Map method, including set, which lets anyone store nonsense counts. You'd have to override set (and remember clear, the constructor, and any methods Map adds in future versions) to keep the class consistent. Other common problems with inheritance:
- Tight coupling. A subclass depends on its parent's internals; a change in the parent can silently break subclasses (the "fragile base class" problem). Article 72's
TypedMapshowed one:Map's constructor calls the overriddenset. - Rigid hierarchies. Each class has exactly one parent. A
FlyingFishthat should be both aFishand aBirddoesn't fit. - Deep chains (
Entity > Model > User > AdminUser > SuperAdmin) make it hard to see where a method is defined.
Composition and delegation
With composition, a class has another object and delegates work to it, exposing only the operations it chooses:
class Tally {
#counts = new Map(); // the helper object, hidden
add(word) {
this.#counts.set(word, this.count(word) + 1);
return this;
}
count(word) {
return this.#counts.get(word) ?? 0;
}
has(word) {
return this.#counts.has(word);
}
get size() {
return this.#counts.size;
}
[Symbol.iterator]() { // iterable like a Set of words
return this.#counts.keys();
}
}
const words = new Tally();
for (const w of "the cat and the hat and the bat".split(" ")) words.add(w);
console.log(words.count("the"), words.count("dog"), words.size);
console.log([...words], words instanceof Map, typeof words.set);
3 0 5
[ 'the', 'cat', 'and', 'hat', 'bat' ] false undefined
There's no way to corrupt the counts, and you could swap the Map for another structure without affecting callers. It's a bit more code (each exposed method is a one-line forwarder), but the class's API is exactly what you designed.

The classic test: use inheritance for "is-a" relationships where the subclass can be used anywhere the parent is expected (a Circle is a Shape, a ValidationError is an Error); use composition for "has-a" or "uses-a" relationships (a Car has an Engine, a Tally uses a Map).
Composing behavior: strategy objects
Composition also lets you plug in behavior at runtime instead of creating a subclass for every variation. Since functions are values, a "strategy" can simply be a function:
class Checkout {
constructor(pricingRule) {
this.pricingRule = pricingRule; // composed behavior
}
total(items) {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
return this.pricingRule(subtotal);
}
}
const regular = (amount) => amount;
const tenPercentOff = (amount) => amount * 0.9;
const bulkDeal = (amount) => (amount > 100 ? amount - 20 : amount);
const cart = [{ price: 60 }, { price: 50 }];
for (const rule of [regular, tenPercentOff, bulkDeal]) {
console.log(new Checkout(rule).total(cart));
}
110
99
90
With inheritance you'd need RegularCheckout, DiscountCheckout and BulkCheckout subclasses, and combining two rules would need yet another class. This is the idea behind dependency injection: pass collaborators in (a logger, an HTTP client, a database) instead of hard-coding them, which also makes classes easy to test with fakes.
Mixins
A mixin is a reusable bundle of methods that can be added to many unrelated classes. JavaScript has two common styles.
Copying methods with Object.assign
const Serializable = {
toJSONString() {
return JSON.stringify(this);
},
};
const Comparable = {
compareTo(other) {
return this.value - other.value;
},
};
class Price {
constructor(value) {
this.value = value;
}
}
Object.assign(Price.prototype, Serializable, Comparable);
const prices = [new Price(30), new Price(10), new Price(20)];
prices.sort((a, b) => a.compareTo(b));
console.log(prices.map((p) => p.value), prices[0].toJSONString());
console.log(Object.keys(Price.prototype));
[ 10, 20, 30 ] {"value":10}
[ 'toJSONString', 'compareTo' ]
Simple, but the copied methods are enumerable (unlike class methods), super inside them doesn't refer to the class's parent, and instanceof Serializable isn't possible. Name clashes are resolved silently: the last mixin wins.
Subclass factories
The more powerful style is a function that takes a class and returns a subclass of it. Because extends accepts any expression, mixins can be stacked:
const Timestamped = (Base) => class Timestamped extends Base {
createdAt = "2026-01-01";
created() {
return `${this.constructor.name} created ${this.createdAt}`;
}
};
const Validated = (Base) => class Validated extends Base {
isValid() {
return Object.values(this).every((v) => v !== "" && v != null);
}
};
class Entity {
constructor(name) {
this.name = name;
}
}
class User extends Validated(Timestamped(Entity)) {
greet() {
return `Hi, ${this.name}`;
}
}
const ana = new User("Ana");
console.log(ana.greet(), "|", ana.created(), "|", ana.isValid(), new User("").isValid());
const chain = [];
for (let p = Object.getPrototypeOf(ana); p; p = Object.getPrototypeOf(p)) {
chain.push(p.constructor.name);
}
console.log(chain.join(" -> "));
Hi, Ana | User created 2026-01-01 | true false
User -> Validated -> Timestamped -> Entity -> Object
Each mixin inserts a class into the prototype chain, so methods are non-enumerable, fields work, super works (a mixin's method can call super.method() and extend whatever class it's applied to), and the order of application decides which version wins. Give the returned class a name, as above, so it shows up in stack traces and debuggers instead of an empty name.
Use mixins sparingly: several stacked mixins recreate the deep-chain problem, and it can be unclear which mixin a method came from. Often a composed helper object is clearer.
Abstract classes and the template method pattern
Sometimes a hierarchy is the right design: several classes share a substantial algorithm and differ only in a few steps. An abstract class implements the shared part and declares the steps that subclasses must supply. JavaScript has no abstract keyword, so you mark abstract methods by throwing (article 72):
class Exporter {
constructor() {
if (new.target === Exporter) throw new TypeError("Exporter is abstract");
}
// abstract step: subclasses must implement
formatRecord(record) {
throw new Error(`${this.constructor.name} must implement formatRecord()`);
}
// optional step with a default
header(records) {
return "";
}
// the template method: the shared algorithm
export(records) {
const lines = records.map((r) => this.formatRecord(r));
const head = this.header(records);
return (head ? [head, ...lines] : lines).join("\n");
}
}
class CsvExporter extends Exporter {
header(records) {
return Object.keys(records[0]).join(",");
}
formatRecord(record) {
return Object.values(record).join(",");
}
}
class JsonLinesExporter extends Exporter {
formatRecord(record) {
return JSON.stringify(record);
}
}
const rows = [{ id: 1, name: "Ana" }, { id: 2, name: "Bo" }];
for (const ExporterClass of [CsvExporter, JsonLinesExporter]) {
console.log(new ExporterClass().export(rows));
}
id,name
1,Ana
2,Bo
{"id":1,"name":"Ana"}
{"id":2,"name":"Bo"}
Code that receives "some exporter" can call export() without knowing which kind it has. Hierarchies can have several abstract levels (for example Exporter > FileExporter > CsvFileExporter), each implementing a bit more, though two or three levels is usually plenty.
Note that the same flexibility is available without inheritance: an Exporter class could take formatRecord and header as constructor arguments (strategy objects). Choose the hierarchy when the variants are real, named kinds with several related methods; choose strategies when they're small, swappable pieces.
Interfaces without an interface keyword
JavaScript has no interface keyword. An "interface" is just an agreed set of methods, and objects satisfy it by having them (duck typing, article 70). The language's own protocols work this way: anything with [Symbol.iterator] is iterable, anything with then is treated as a promise-like "thenable" (part 13), and anything with toJSON controls its JSON form.
A small helper can check an object at a boundary:
const implementsAll = (obj, ...methods) => methods.every((m) => typeof obj?.[m] === "function");
const memoryCache = { get() {}, set() {}, delete() {} };
const brokenCache = { get() {} };
console.log(implementsAll(memoryCache, "get", "set", "delete"), implementsAll(brokenCache, "get", "set"));
true false
TypeScript adds real interfaces checked before the code runs, and they disappear from the JavaScript output (part 17).
Decorators: wrapping methods declaratively
A decorator wraps a class or class member with extra behavior: logging, validation, caching or registering. It's written with @:
class Greeter {
@logged
greet(name: string) {
return `Hello, ${name}!`;
}
}
Decorators are a TC39 proposal (Stage 2.7 at the time of writing), so engines don't run them natively yet. TypeScript (since version 5) and Babel compile them, and frameworks such as Angular, Lit and NestJS use them heavily. TypeScript's older experimentalDecorators setting implements an earlier, incompatible design, which is common in existing code.
Under the syntax, a method decorator is an ordinary function. It receives the original method and a context object (with kind, name and more) and returns the replacement. That's composition again: the wrapper adds behavior around the original, like the higher-order functions of article 69.
// A decorator is a function that receives the decorated method and a context
// object, and returns a replacement. The syntax `@logged greet() {...}` calls it
// for you when the class is defined; here we apply it by hand.
function logged(method, context) {
return function (...args) {
console.log(`-> ${context.name}(${args.join(", ")})`);
const result = method.apply(this, args);
console.log(`<- ${context.name} returned ${JSON.stringify(result)}`);
return result;
};
}
class Greeter {
constructor(greeting) { this.greeting = greeting; }
greet(name) { return `${this.greeting}, ${name}!`; }
}
// What `@logged` on greet would do:
Greeter.prototype.greet = logged(Greeter.prototype.greet, { kind: "method", name: "greet" });
const g = new Greeter("Hello");
g.greet("Ada");
-> greet(Ada)
<- greet returned "Hello, Ada!"
Choosing a design
| Situation | Good fit |
|---|---|
| A is a genuine kind of B and can be used wherever B is | class A extends B |
| A uses B to do its job | composition: store a B in a (private) field |
| Behavior varies and should be swappable | strategy objects or functions passed in |
| Several unrelated classes need the same small capability | mixin, or a shared helper function |
| Several classes share an algorithm and differ in a few steps | abstract base class with a template method |
| Callers only need "something with these methods" | duck-typed interface |
And a few rules of thumb: keep hierarchies shallow; don't extend a class just to reuse a couple of its methods; never call overridable methods from a constructor; and remember that many JavaScript programs need few classes at all, since plain objects, closures and modules (next part) cover a lot of ground.
Common questions
Is inheritance bad?
No, overused inheritance is. Error types, UI component frameworks, and genuine "is-a" families are good uses. The guideline is to reach for composition first and use inheritance when the relationship really is "is-a".
What's the difference between a mixin and multiple inheritance?
Multiple inheritance gives a class several parents at once. Subclass-factory mixins build a single linear chain (User, Validated, Timestamped, Entity), so lookup order is always clear; the last-applied mixin is closest to the class and wins conflicts.
Should I use #private fields for composed helpers?
Usually yes. Hiding the helper (#counts) keeps callers from depending on it, which is the whole point of composition: you can replace the helper later without changing the class's API.
Why not just use object literals and functions instead of classes?
That's a valid style, especially for one-off objects and functional code. Classes shine when you create many objects of the same kind, want instanceof checks, private fields, or a framework expects them.
Summary
- Inheritance shares everything the parent has, couples subclass to parent internals, and allows only one parent; use it for genuine "is-a" relationships.
- Composition stores helper objects (often in private fields) and delegates to them, exposing only a deliberate API; strategies and dependency injection plug in behavior.
Object.assign(Class.prototype, mixin)copies methods simply; subclass-factory mixins (Base => class extends Base) stack behaviors in one chain with workingsuper.- Abstract base classes implement shared algorithms (template methods) and leave specific steps to subclasses, marked by throwing.
- Interfaces in JavaScript are agreed sets of methods checked by duck typing.
Review quiz
Test yourself on everything in this part, from prototypes and constructor functions to class fields, private members, subclasses and composition: Part 9 review quiz: Classes.
Practice Questions
Why does class Stack extends Array make a poor stack?
Answer
It inherits every array method, so callers can splice, shift, sort or index into the middle, breaking the "last in, first out" rule. A Stack class that keeps a private array and exposes only push, pop, peek and size enforces it.
In class A extends M2(M1(Base)), where both mixins define describe(), which version does new A().describe() use?
Answer
M2's. The chain is A, M2's class, M1's class, Base; lookup finds the closest definition first. M2's version could call super.describe() to reach M1's.
Turn this subclass-per-variant design into composition: class EmailNotifier extends Notifier, class SmsNotifier extends Notifier, each overriding only send(message).
Answer
Give Notifier a channel collaborator: the code below, then new Notifier(emailChannel) or new Notifier(smsChannel), where each channel is any object with a send method.
class Notifier {
constructor(channel) {
this.channel = channel;
}
notify(msg) {
return this.channel.send(msg);
}
}
What's printed by Object.keys(Price.prototype) after this code, if Price also has a class method b()?
Object.assign(Price.prototype, { a() {} })
Answer
[ 'a' ]. The copied method is enumerable; class methods are not.
Previous: JavaScript Subclasses: extends, super, Overriding Methods and Extending Built-ins
Next: JavaScript Modules Explained: Why Modules Exist, IIFEs, Closures and CommonJS require

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.