Hello! Welcome to your next lesson in the "Compositional Patterns" module.
In our last session, we analyzed the critical trade-offs between inheritance and composition. We established the principle of "favoring composition over inheritance" to create more flexible, decoupled, and robust systems. You learned to use the "IS-A" vs. "HAS-A" heuristic and the Liskov Substitution Principle as a framework for making sound design decisions.
Today, we transition from the why to the how. Our goal is to implement a simple mixin pattern by merging properties using Object.assign. A mixin is one of the most direct and common ways to achieve composition in JavaScript, allowing you to "mix in" reusable behaviors to objects or classes without using inheritance.
What is a Mixin?
A mixin is an object that contains a bundle of methods and properties. Its purpose is not to be used on its own, but to add its functionality to other objects. Think of it as a "pack" of abilities you can give to any object that needs them.

Let's start with a short video that introduces the concept using a fun analogy and demonstrates the basic implementation.
Mixins in JavaScript : Object Oriented Programming Series - Part 8
The video 'Mixins in JavaScript' from the techsith channel provides a great analogy for mixins using an ice cream shop. It then shows how to combine different 'skill' objects into an 'engineer' object using Object.assign.
Please watch the first part of the video, from the beginning to 06:18. Focus on how separate objects (jsSkill, engDegree) are created and then merged into a new object. The rest of the video explores functional mixins, which we'll cover in our next lesson.
The Core Mechanism: Object.assign()
As you saw in the video, the key tool for this simple mixin pattern is Object.assign(). Given your CS background, you can think of it as a function that performs a shallow copy of properties from one or more source objects onto a target object.
The signature is Object.assign(target, ...sources).
target: The object to which properties will be copied. This object is mutated....sources: One or more source objects from which to copy properties.
Properties in later source objects will overwrite properties with the same key in earlier ones.

Implementing the Pattern: Two Common Approaches
There are two primary ways to use this simple mixin pattern:
- Adding functionality to a class's prototype.
- Composing a new object from scratch using a factory function.
Let's explore both.
1. Mixing into a Class Prototype
This is a very common use case. You have a class, and you want all instances of that class to share a certain set of behaviors, but those behaviors don't belong in a parent class.
For example, let's say we have several classes in our application (User, Document, Project) and we want all of them to be "commentable."
First, we define the mixin—a plain object containing the desired functionality.
const commentable = {
addComment(comment) {
if (!this.comments) {
this.comments = [];
}
this.comments.push(comment);
console.log(`Comment added to ${this.name}.`);
},
viewComments() {
console.log(`--- Comments for ${this.name} ---`);
(this.comments || []).forEach((c, i) => console.log(`${i+1}: ${c}`));
}
};
Notice that the methods in commentable rely on a this context. They expect this to have a name property and they manage a comments property on this.
Now, let's create a User class and mix in the commentable behavior.
class User {
constructor(name) {
this.name = name;
}
}
// Use Object.assign to copy the methods to the User's prototype
Object.assign(User.prototype, commentable);
// Now, all User instances have the commentable methods
const user = new User("Alice");
user.addComment("Great work on the project!");
user.addComment("Don't forget the deadline is Friday.");
user.viewComments();
/*
Output:
Comment added to Alice.
Comment added to Alice.
--- Comments for Alice ---
1: Great work on the project!
2: Don't forget the deadline is Friday.
*/
By merging commentable into User.prototype, we've efficiently added the behavior to every User instance without using inheritance. We could do the same for a Document class, reusing the exact same mixin.
For a more detailed walkthrough and another excellent example (eventMixin), please read the following article.
The article 'Mixins' from the javascript.info website is a classic resource on this topic. It clearly explains the concept and provides a very practical eventMixin example that shows how you can grant event-emitter capabilities to any class.
Read the entire article. Pay special attention to: The simple sayHiMixin example. The implementation of the real-world eventMixin and how it's applied to the Menu class. The summary's point about potential naming conflicts, which is the main drawback of this simple pattern.
Test your understanding!
You are building a simple game. You have a Player class and an Enemy class.
class Player {
constructor(name, health) {
this.name = name;
this.health = health;
}
}
class Enemy {
constructor(type, health) {
this.name = type;
this.health = health;
}
}
Create a health mixin that provides two methods:
takeDamage(amount): Reduces health by the given amount.heal(amount): Increases health by the given amount.
Apply this mixin to both the Player and Enemy classes so that instances of both can use these methods.
Show answer
First, define the health mixin.
const healthMixin = {
takeDamage(amount) {
this.health -= amount;
console.log(`${this.name} took ${amount} damage, health is now ${this.health}.`);
},
heal(amount) {
this.health += amount;
console.log(`${this.name} healed for ${amount}, health is now ${this.health}.`);
}
};
Next, apply the mixin to the prototypes of both classes using Object.assign.
// Apply to Player
Object.assign(Player.prototype, healthMixin);
// Apply to Enemy
Object.assign(Enemy.prototype, healthMixin);
// --- Verification ---
const hero = new Player("Hero", 100);
const goblin = new Enemy("Goblin", 30);
hero.takeDamage(15); // Hero took 15 damage, health is now 85.
goblin.takeDamage(20); // Goblin took 20 damage, health is now 10.
hero.heal(10); // Hero healed for 10, health is now 95.
2. Composing Objects with a Factory Function
This approach aligns perfectly with the "composition over inheritance" philosophy we discussed in the last lesson. Instead of adding methods to a class, we build an object from scratch by combining several behavior objects. This is often done inside a factory function.
This pattern offers maximum flexibility, as each object can be composed with a unique set of behaviors.
Let's watch a video that demonstrates this pattern elegantly. It follows the same logic as the "monster creator" example from our previous lesson.
Composition vs Inheritance in JavaScript
In 'Composition vs Inheritance' by Steve Griffith, the presenter builds on the problems with inheritance by showing how to compose objects using small, single-functionality units. This directly illustrates the factory function approach.
Watch from 05:39 to 10:10. Observe how behaviors like talker, walker, and wifier are defined as functions that return objects with methods. Then, see how a person or cyborg is created using Object.assign to combine these behaviors into a new object.
As you saw, the factory function (person in the video) becomes a recipe for creating an object. It takes some initial state (like name) and then uses Object.assign to bolt on the desired behaviors.
// A simple example inspired by the video
const talker = {
talk() {
console.log(`Hello, my name is ${this.name}.`);
}
};
const walker = {
walk() {
console.log(`${this.name} is walking.`);
}
};
// Factory function to create a person
function createPerson(name) {
// Start with a state object, then mix in the behaviors
return Object.assign({ name }, talker, walker);
}
const bob = createPerson("Bob");
bob.talk(); // Hello, my name is Bob.
bob.walk(); // Bob is walking.
The biggest advantage here is the extreme flexibility. Want to create a non-talking Robot that can walk?
function createRobot(id) {
return Object.assign({ name: `Robot #${id}` }, walker);
}
const unit734 = createRobot(734);
unit734.walk(); // Robot #734 is walking.
// unit734.talk(); // TypeError: unit734.talk is not a function
A Word of Caution: Name Collisions
The primary drawback of this simple mixin pattern is name collision. If a class or another mixin already has a property with the same name as one you are mixing in, it will be overwritten. The last one in the Object.assign call wins.
const myObject = { x: 1 };
const mixinA = { x: 2, y: 3 };
const mixinB = { y: 4, z: 5 };
Object.assign(myObject, mixinA, mixinB);
console.log(myObject); // { x: 2, y: 4, z: 5 }
// mixinA's 'x' overwrote myObject's 'x'.
// mixinB's 'y' overwrote mixinA's 'y'.
This is why care must be taken when naming methods in mixins. More advanced mixin patterns, which we will explore later, can help manage or prevent these collisions.
Conclusion
Today we took our first practical step into the world of composition. We saw that mixins provide a powerful way to reuse code and add behavior to objects without the rigidity of inheritance.
Key Takeaways:
- A mixin is an object containing methods and properties intended to be "mixed into" other objects.
Object.assign(target, ...sources)is the core mechanism for implementing simple mixins, as it copies properties from sources to a target.- You can apply mixins to a class prototype to grant shared behavior to all instances of that class.
- Alternatively, you can use mixins within a factory function to compose individual objects with custom sets of behaviors, offering maximum flexibility.
- Be mindful of name collisions, as properties from later sources in an
Object.assigncall will overwrite earlier ones.
Next Up
This simple mixin pattern is powerful, but it's also stateless. The commentable and health mixins relied on the target object to hold the state (this.comments, this.health). What if we want the mixin itself to encapsulate its own state?
In our next lesson, we will create functional mixins that can be applied to any class. This advanced pattern uses closures to create stateful, encapsulated behaviors, taking our composition skills to the next level.