Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 156 ยท Classes and Objects in Depth

Composition over Inheritance

Build JavaScript objects from small behaviors with delegation, factory functions, mixins and passed-in functions, and learn when a class is the right tool.

Inheritance answers the question "what is this object?" A SavingsAccount is an Account. That works well while the world fits neatly into a tree. Real software rarely does. Sooner or later you need a thing that is a little bit of this and a little bit of that, and a single-parent class tree can't express it.

Composition asks a different question: "what can this object do, and what is it made of?" Instead of inheriting behavior from a parent, an object is assembled from smaller, independent parts. The phrase "favor composition over inheritance" is one of the most repeated pieces of advice in object-oriented design. This lesson shows why, walks through the main ways to compose behavior in JavaScript (delegation, factory functions, mixins and passing functions in), and ends with practical guidance on when a class is the right tool at all.

Where inheritance breaks down

Imagine a small game. You start with a sensible hierarchy:

TEXT
Character
โ”œโ”€โ”€ Walker      (can walk)
โ”œโ”€โ”€ Swimmer     (can swim)
โ””โ”€โ”€ Flyer       (can fly)

Then the designer asks for a duck, which walks, swims and flies. And a penguin, which walks and swims but doesn't fly. And a flying fish. A class can only extends one parent, so you end up copying methods between classes or building an ever-deeper tree like WalkingSwimmingFlyer. Every new combination makes the tree worse.

Inheritance has a few other costs worth naming:

  • Tight coupling. A subclass depends on the internal details of its parent. A harmless-looking change in the parent can break children you have never seen. This is sometimes called the fragile base class problem.
  • Getting more than you asked for. Inheriting gives a child everything the parent has, including methods that make no sense for it.
  • Decisions made too early. The hierarchy captures your understanding on day one, and real requirements tend to cut across it.

Composition avoids all three by keeping each ability separate and combining only what each object needs.

Has-a instead of is-a: delegation

The simplest form of composition is an object that holds another object and hands work to it. This is called delegation. A car isn't a kind of engine; a car has an engine:

JS Delegation: an object that has parts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because Car receives its parts through the constructor, you can swap in a different engine, or a fake one in a test, without changing Car. That small idea, called dependency injection, is one of the biggest practical wins of composition.

Factory functions and small behaviors

You don't need classes to compose objects. A factory function is an ordinary function that builds and returns an object. Combine it with small functions that each add one ability, and the duck problem from earlier disappears:

JS Composing abilities with factory functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each ability lives in exactly one place, and any creature can use any combination. Adding a flying fish is two lines. The state object is captured by the arrow functions through a closure, so it stays private to each creature with no # needed.

The trade-off: each object gets its own copies of its methods instead of sharing them through a prototype. For a few hundred objects that doesn't matter. For hundreds of thousands, classes are more memory-efficient.

Mixins: adding behavior to classes

When you do use classes, a mixin lets several unrelated classes share a bundle of methods without a common parent. The simplest mixin is an object of methods copied onto a class's prototype with Object.assign:

JavaScript
const serializable = {
  toJSON() { return { type: this.constructor.name, ...this }; },
};

class Note { constructor(text) { this.text = text; } }
Object.assign(Note.prototype, serializable);

A more powerful form is the subclass factory: a function that takes a class and returns a new class extending it. Because each mixin returns a class, you can stack as many as you like:

JS Subclass-factory mixins

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Mixins are handy, but they are still inheritance underneath: Article sits on top of a chain of anonymous classes, and two mixins that define the same method name will silently override each other. Use them for small, well-named capabilities, and keep the stack short.

Passing behavior in as functions

Often the simplest composition of all is to pass a function where you might otherwise create a subclass. If the only thing that differs between variations is one step of an algorithm, make that step a parameter. You already do this every time you give sort() a comparator or filter() a callback (see Higher-Order Functions).

JS Strategies instead of subclasses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is known as the strategy pattern. One Cart class supports any discount rule anyone will ever invent, and the rule can even change while the program runs.

So when should you use a class?

JavaScript is unusual: it gives you classes, prototypes, closures and plain objects, and none of them is "the right way". Here is a practical guide.

A class is a good choice when:

  • You create many objects with the same shape and behavior, so sharing methods on a prototype pays off.
  • Objects hold state that changes over time and must stay valid, which private fields and setters protect.
  • There is a genuine, stable is-a relationship, such as custom Error types, or a framework expects you to extend its base class (web components extend HTMLElement, for example).

Plain functions and objects are often better when:

  • You are transforming data: input in, output out, no lasting state. A function is simpler than a class with one method.
  • You have a single object, like a configuration or a module's API. An object literal or a module is enough.
  • You would be creating a class only to group static helpers. Export the functions instead.

And whichever you choose:

  • Prefer has-a (delegation) over is-a when you're unsure; it's easier to change later.
  • Keep any inheritance shallow, one or two levels.
  • Combine small, focused pieces instead of building one large object that does everything.

None of this means inheritance is bad. It means inheritance is the strongest kind of coupling between two pieces of code, so reach for it deliberately rather than by default.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the core idea of composition?

    Composition assembles an object from parts (what it has and can do) instead of inheriting everything from a parent class.
  2. 2. A Car stores an engine object and calls this.engine.start(). What is this technique called?

    The car delegates the work to the object it holds. That is a has-a relationship, the simplest form of composition.
  3. 3. What does const Taggable = (Base) => class extends Base { ... } define?

    It is a function that takes a class and returns a new class extending it, so you can stack capabilities like Taggable(Timestamped(Entry)).
  4. 4. Different carts need different discount rules. Which approach avoids creating a subclass per rule?

    Passing the rule in as a function (the strategy pattern) lets one Cart class support any rule, and even switch rules at runtime.
  5. 5. In which situation is a class clearly a good fit?

    Classes shine when many instances share methods through the prototype and manage their own state. The other cases are simpler as functions, objects or modules.

Summary

  • Inheritance models is-a; composition models has-a and can-do, and copes far better with combinations.
  • Delegation: an object holds other objects and hands work to them; passing parts in makes them easy to swap and test.
  • Factory functions with small ability functions build objects from exactly the behaviors they need, with closures for privacy.
  • Mixins, either Object.assign onto a prototype or subclass factories, share methods across unrelated classes; keep them small.
  • Passing functions in (the strategy pattern) often replaces a whole family of subclasses.
  • Use classes for many stateful objects and genuine is-a relationships; use plain functions and objects for everything else.

Next: OOP Principles in JavaScript.