The Mixin Pattern
You'll learn how mixins copy methods from behavior objects into target objects, enabling code reuse without inheritance hierarchies.
What Is a Mixin?
A mixin is an object containing methods you want to share across multiple objects. Instead of inheriting from a parent class, you copy these methods directly into your target objects. Think of it like adding plugins to a device—each plugin adds specific functionality without changing what the device fundamentally is.
How Mixins Work
You create a plain object with reusable methods, then use Object.assign() or spread syntax to merge those methods into your target:
const canEat = {
eat(food) {
console.log(`Eating ${food}`);
}
};
const canSwim = {
swim() {
console.log('Swimming...');
}
};
const duck = Object.assign(
{},
canEat,
canSwim,
{ name: 'Donald' }
);
duck.eat('bread'); // "Eating bread"
duck.swim(); // "Swimming..."
Why Mixins Matter
Mixins enable horizontal composition. Instead of forcing objects into rigid parent-child relationships, you pick and choose capabilities:
const robot = Object.assign({}, canSwim, { model: 'X-1' });
// Robot can swim but doesn't need to eat
const person = Object.assign({}, canEat, { name: 'Alice' });
// Person can eat but doesn't swim
Each object gets exactly the methods it needs. You avoid awkward inheritance trees where a "FlyingSwimmingEatingRobot" class would be absurd.
Flexibility Over Hierarchy
Mixins shine when objects need overlapping but non-identical functionality. You compose behavior across objects rather than down a tree.
Key Takeaway: Mixins copy methods from behavior objects into targets using Object.assign(), letting you compose functionality horizontally instead of inheriting vertically.