Avoiding Mixin Name Collisions
You'll learn how to safely compose multiple mixins without property names clashing and overwriting each other.
The Collision Problem
When you apply multiple mixins to the same object, they might define properties or methods with identical names. The last mixin wins, silently overwriting earlier ones—a bug waiting to happen:
const canFly = {
move() { return "flying"; }
};
const canSwim = {
move() { return "swimming"; }
};
const duck = Object.assign({}, canFly, canSwim);
duck.move(); // "swimming" — canFly's move() is lost!
Solution 1: Namespacing
Group each mixin's methods under a unique property name:
const canFly = {
flight: {
move() { return "flying"; }
}
};
const canSwim = {
swimming: {
move() { return "swimming"; }
}
};
const duck = Object.assign({}, canFly, canSwim);
duck.flight.move(); // "flying"
duck.swimming.move(); // "swimming"
Now both behaviors coexist peacefully. The trade-off: slightly more verbose access.
Solution 2: Symbol Keys
Use symbols to guarantee uniqueness:
const flyMove = Symbol('move');
const swimMove = Symbol('move');
const canFly = {
[flyMove]() { return "flying"; }
};
const canSwim = {
[swimMove]() { return "swimming"; }
};
const duck = Object.assign({}, canFly, canSwim);
duck[flyMove](); // "flying"
duck[swimMove](); // "swimming"
Symbols are completely unique—no collision possible. However, they're not enumerable by default and require holding references.
Which to Use?
- Namespacing: Best when you want readable, discoverable property access
- Symbols: Best when you need absolute uniqueness and privacy
Key Takeaway: Always anticipate name collisions when composing mixins—use namespacing for clarity or symbol keys for guaranteed uniqueness.