SyntaxStudy
Sign Up
JavaScript Mixins and Composition Patterns
JavaScript Advanced 10 min read

Mixins and Composition Patterns

Mixins and Composition Patterns

JavaScript only supports single inheritance — a class can extend only one parent. Mixins are a pattern for sharing behaviour across unrelated class hierarchies by composing functionality rather than inheriting it, following the principle "favour composition over inheritance."

Function-based Mixins

A mixin is typically a function that takes a class as an argument and returns a new class with additional methods added. This pattern uses the fact that extends can take any expression that evaluates to a class.

Object.assign Mixins

A simpler approach copies methods from a plain object onto a class prototype using Object.assign(MyClass.prototype, mixinMethods). This is less flexible but sufficient for many cases.

When to Use Mixins

Use mixins when multiple unrelated classes need the same behaviour (serialisation, event emission, logging) and a shared base class would create an unnatural or overly rigid hierarchy.

Example
const Serializable = (Base) => class extends Base {
  serialize() {
    return JSON.stringify(this);
  }
  static deserialize(json) {
    return Object.assign(new this(), JSON.parse(json));
  }
};
const Loggable = (Base) => class extends Base {
  log(msg) {
    console.log("[" + this.constructor.name + "] " + msg);
  }
};
class Entity {
  constructor(id) { this.id = id; }
}
class User extends Serializable(Loggable(Entity)) {
  constructor(id, name) {
    super(id);
    this.name = name;
  }
}
const u = new User(1, 'Alice');
u.log('created');       // [User] created
console.log(u.serialize()); // JSON string
console.log(u instanceof Entity); // true
Pro Tip

Keep each mixin focused on a single concern — a Serializable mixin should only serialise, a Loggable mixin should only log. Mixing multiple concerns into one mixin recreates the coupling you were trying to avoid with inheritance.