Functional Mixins
You'll learn how to build mixins as composable functions that augment and return objects for flexible behavior chaining.
What Are Functional Mixins?
Functional mixins are functions that accept an object, add properties or methods to it, and then return that enhanced object. Unlike the Object.assign-based mixins you've seen, functional mixins give you:
- Chaining: Return the object so multiple mixins can be applied in sequence
- Privacy: Use closures to create truly private data
- Logic: Conditional behavior based on the object's state
- Composition: Build complex objects from simple, reusable functions
Think of functional mixins like assembly line stations—each station (mixin) receives the product (object), adds its specific enhancement, and passes it along to the next station.
Basic Structure
const canFly = (obj) => {
obj.fly = () => console.log('Flying!');
return obj; // Enable chaining
};
const canSwim = (obj) => {
obj.swim = () => console.log('Swimming!');
return obj;
};
// Chain multiple mixins
const duck = canSwim(canFly({}));
duck.fly(); // "Flying!"
duck.swim(); // "Swimming!"
Mixins with Private State
const withSpeed = (obj) => {
let speed = 0; // Private variable
obj.accelerate = () => speed += 10;
obj.getSpeed = () => speed;
return obj;
};
const car = withSpeed({});
car.accelerate();
console.log(car.getSpeed()); // 10
console.log(car.speed); // undefined (private!)
Functional Composition Pattern
const compose = (...mixins) => (obj) =>
mixins.reduce((acc, mixin) => mixin(acc), obj);
const createDuck = compose(canFly, canSwim, withSpeed);
const myDuck = createDuck({});
Key Takeaway: Functional mixins are functions that accept objects, enhance them with new capabilities, and return them for chaining—offering cleaner composition than class inheritance and more power than simple Object.assign.