Composition with Object Literals
You'll learn how to combine multiple plain objects into one using object literals and Object.assign to compose flexible, reusable behaviors.
The Core Idea
Instead of building complex inheritance chains, you can compose objects by mixing together simple object literals that each provide specific behaviors. Think of it like building with LEGO blocks—each piece (object literal) has a focused purpose, and you snap them together to create exactly what you need.
How It Works
You create separate objects that each contain related methods or properties, then use Object.assign to merge them into a single composed object:
const canEat = {
eat(food) {
console.log(`Eating ${food}`);
}
};
const canWalk = {
walk() {
console.log('Walking...');
}
};
const canSwim = {
swim() {
console.log('Swimming...');
}
};
// Compose a duck: eats, walks, and swims
const duck = Object.assign({}, canEat, canWalk, canSwim);
duck.eat('bread'); // "Eating bread"
duck.swim(); // "Swimming..."
// Compose a human: eats and walks, but doesn't swim
const human = Object.assign({}, canEat, canWalk);
human.eat('pizza'); // "Eating pizza"
human.walk(); // "Walking..."
// human.swim is undefined
Why This Matters
This approach gives you maximum flexibility. You pick and choose exactly which behaviors each object needs, without forcing them into rigid class hierarchies. Need a new combination? Just mix different object literals together.
Key Takeaway: Composing objects with Object.assign and plain object literals lets you build flexible, customized objects by selecting only the behaviors you need from multiple sources—no inheritance required.