JS Mixins
In this page:
What Is a Mixin?
A mixin is a way to add reusable methods from one object to another object. Since JavaScript only supports single inheritance through the prototype chain, mixins are the common workaround for combining behavior from multiple independent sources.
Example: What Is a Mixin?
const canFly = { fly() { console.log("Flying"); } };
const bird = {};
Object.assign(bird, canFly);
bird.fly();
Multiple Mixins
You can combine methods from several mixin objects into one target object. Object.assign(target, mixin1, mixin2) is the typical way to apply several mixins at once, copying each one's own enumerable properties onto the target object.
Example: Multiple Mixins
const canSwim = { swim() { console.log("Swimming"); } };
const canFly = { fly() { console.log("Flying"); } };
const duck = {};
Object.assign(duck, canSwim, canFly);
duck.swim();
duck.fly();
Mixin Methods with this
Mixin methods can use this to access properties on the object that receives the methods. Since Object.assign copies properties directly onto the target, methods added by a mixin behave exactly like methods defined on the object itself, including their this binding.
Example: Mixin Methods with this
const canGreet = { greet() { console.log("Hi, I'm " + this.name); } };
const user = { name: "Sam" };
Object.assign(user, canGreet);
user.greet();
Avoiding Duplicate Code
Mixins help share small pieces of behavior. They are useful when a class hierarchy does not fit the problem. This avoids duplicating the same method definition across many unrelated classes, keeping a single source of truth for that piece of shared behavior.
Example: Avoiding Duplicate Code
const canFly = { fly() { console.log(this.name + " flies"); } };
class Bird { constructor(name) { this.name = name; } }
Object.assign(Bird.prototype, canFly);
new Bird("Tweety").fly();
Mixin with a Factory
A factory function can create objects and apply useful mixins to them. A factory function that applies mixins on creation guarantees every object built by that factory consistently gets the same combined behavior.
Example: Mixin with a Factory
const canFly = { fly() { console.log("Flying"); } };
function createBird(name) {
const bird = { name };
return Object.assign(bird, canFly);
}
createBird("Robin").fly();
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: