Implementing Mixins with Object.assign
You'll learn how to use Object.assign to compose objects by merging behavior from multiple mixins into a single target.
The Core Idea
A mixin is just a plain object containing methods you want to share. Instead of building a complex inheritance tree, you can copy properties from one or more mixin objects into your target object. Object.assign is the perfect tool for this—it copies all enumerable properties from source objects into a target.
Think of it like assembling a custom toolbox: you take tools from different kits (mixins) and combine them into one box (your object). No rigid hierarchy required.
Basic Pattern
const canFly = {
fly() {
console.log(`${this.name} is flying!`);
}
};
const canSwim = {
swim() {
console.log(`${this.name} is swimming!`);
}
};
function createDuck(name) {
const duck = { name };
Object.assign(duck, canFly, canSwim);
return duck;
}
const mallard = createDuck('Mallard');
mallard.fly(); // "Mallard is flying!"
mallard.swim(); // "Mallard is swimming!"
Object.assign(duck, canFly, canSwim) copies all methods from both mixins into the duck object. Order matters—if mixins have conflicting property names, later ones overwrite earlier ones.
Multiple Mixins Example
const logger = {
log(message) {
console.log(`[${this.name}]: ${message}`);
}
};
function createRobot(name) {
const robot = { name };
Object.assign(robot, canFly, logger);
return robot;
}
const bot = createRobot('Bot-X');
bot.fly(); // "Bot-X is flying!"
bot.log('Ready'); // "[Bot-X]: Ready"
Key Takeaway: Object.assign enables mixins by merging multiple source objects into a target, allowing you to compose flexible objects with behavior from different sources without inheritance chains.