Composition vs Inheritance in JavaScript
There are two common ways to share behaviour between objects. With inheritance, an object gets its methods from a parent type, and the types form a tree: a lamp is an appliance. With composition, an object is assembled from small, independent pieces of behaviour: an oven can switch on, can heat and can run a timer.
Inheritance is simple while every type fits neatly into one branch of the tree. Composition copes better when a new type needs behaviour from several branches at once, which is why the advice “favour composition over inheritance” is common.
Inheritance
Section titled “Inheritance”Here each appliance type extends a shared parent class, and each adds the method that only it needs:
class Appliance { constructor(name) { this.name = name; } describe() { return `This is the ${this.name}`; }}
class Lamp extends Appliance { switchOn() { return `${this.name} is on`; }}
class Heater extends Appliance { setTemperature(degrees) { return `${this.name} set to ${degrees}°C`; }}
const lamp = new Lamp('desk lamp');console.log(lamp.describe());console.log(lamp.switchOn());
const heater = new Heater('radiator');console.log(heater.setTemperature(20));console.log(typeof heater.switchOn);This prints:
This is the desk lampdesk lamp is onradiator set to 20°CundefinedWhere the hierarchy strains
Section titled “Where the hierarchy strains”Now suppose you need an oven, which switches on like a lamp and has a temperature like a heater. It cannot extend both classes, so the choices are all awkward:
- copy
switchOn()into a newOvenclass, so the same code lives in two places - move
switchOn()up intoAppliance, so the radiator gets a method it should not have - add an intermediate class such as
SwitchableHeater, which makes the tree deeper each time a new combination appears
The trouble is that the tree forces you to decide early what each type is, while the new requirement is about what it does.
Composition
Section titled “Composition”With composition, each behaviour is a small function that takes the object’s state and returns the methods for that behaviour. A factory function then builds an object from whichever behaviours it needs, using spread syntax to combine them:
const switchable = (state) => ({ switchOn() { state.on = true; return `${state.name} is on`; },});
const heatable = (state) => ({ setTemperature(degrees) { state.temperature = degrees; return `${state.name} set to ${degrees}°C`; },});
const timed = (state) => ({ setTimer(minutes) { return `${state.name} will stop in ${minutes} minutes`; },});
const createLamp = (name) => { const state = { name, on: false }; return { ...switchable(state) };};
const createOven = (name) => { const state = { name, on: false, temperature: 0 }; return { ...switchable(state), ...heatable(state), ...timed(state) };};
const lamp = createLamp('desk lamp');console.log(lamp.switchOn());
const oven = createOven('oven');console.log(oven.switchOn());console.log(oven.setTemperature(180));console.log(oven.setTimer(25));console.log(Object.keys(oven));This prints:
desk lamp is onoven is onoven set to 180°Coven will stop in 25 minutes[ 'switchOn', 'setTemperature', 'setTimer' ]The oven takes exactly the three behaviours it needs, and a new combination is one more factory rather than a change to a hierarchy. Because state is a local variable that the methods close over, it is also private: code outside can change it only through those methods. Object.assign({}, switchable(state), heatable(state)) does the same job as the spread and is common in older code.
Choosing between them
Section titled “Choosing between them”The two approaches are not exclusive. A sensible rule is to reach for inheritance when the relationship really is “is a” and the tree is shallow and stable, and to use composition when objects mix and match abilities. Composition also works with classes, by giving an object other objects as properties, so a Car class can hold an Engine object rather than extending one.
Each composed object gets its own copy of every method, while instances of a class share methods through their prototype. That costs a little memory, which only matters when you create very large numbers of objects. Prototypes explains how that sharing works.
Steve Griffith covers this topic in his video Composition vs Inheritance in JavaScript.