Functional Mixins for Safer Composition
What you'll learn: How to use mixins as functions that accept parameters and augment objects, avoiding the shared state pitfalls of simple object mixins.
The Problem with Object-Based Mixins
When you use Object.assign to apply mixins directly, all objects share the same mixin methods. If those methods reference shared state or lack flexibility, you can run into subtle bugs. Functional mixins solve this by treating mixins as factory functions that can accept parameters and create fresh behavior for each object.
How Functional Mixins Work
Instead of passing a plain object to Object.assign, you pass a function that:
- Accepts the target object as its first parameter
- Optionally accepts configuration parameters
- Augments and returns the target object
This gives you parameterized behavior and eliminates shared state issues.
const canFly = (obj, maxAltitude) => {
return Object.assign(obj, {
fly() {
console.log(`Flying up to ${maxAltitude} feet!`);
},
maxAltitude
});
};
const canSwim = (obj, speed) => {
return Object.assign(obj, {
swim() {
console.log(`Swimming at ${speed} mph!`);
}
});
};
// Create objects with customized mixins
const duck = canSwim(canFly({name: 'Donald'}, 5000), 2);
const eagle = canFly({name: 'Freedom'}, 20000);
duck.fly(); // Flying up to 5000 feet!
duck.swim(); // Swimming at 2 mph!
eagle.fly(); // Flying up to 20000 feet!
Each object gets its own configured behavior—no shared state, and the mixin logic can adapt based on parameters.
Composition Safety
Because each functional mixin returns the augmented object, you can chain them safely. Each receives parameters specific to that capability, making your composition explicit and flexible.
Key Takeaway: Functional mixins are functions that augment objects with parameterized behavior, eliminating shared state issues and enabling safer, more flexible composition than plain object mixins.