Skip to content
jshacks.dev
Patterns

The Mixin Pattern in JavaScript Explained

Mixins add shared behavior to a class without inheritance. See Object.assign mixins, subclass factory mixins, and where they cause naming collisions.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Vite, npm and Node.js logos.

A mixin is a way to share behavior between classes that do not share a parent. JavaScript classes can extend only one class, so when two unrelated classes both need toJSON() or emit(), you copy that behavior in from a mixin. This post covers the two common forms on Node.js 24, Object.assign onto a prototype and a function that returns a subclass, shows how they combine, and names the pitfalls: collisions, hidden dependencies and debugging.

The problem: single inheritance

Say a User and an Invoice both need to be turned into JSON with a type tag, but they have nothing else in common.

duplicated.mjsJavaScript
class User {
  constructor(name) {
    this.name = name;
  }
  toJSON() {
    return { type: "User", ...this };
  }
}

class Invoice {
  constructor(total) {
    this.total = total;
  }
  toJSON() {
    return { type: "Invoice", ...this };
  }
}

console.log(JSON.stringify(new User("Ada")));
console.log(JSON.stringify(new Invoice(40)));
Text
{"type":"User","name":"Ada"}
{"type":"Invoice","total":40}

The two toJSON methods differ only in a string. Making Invoice extend User to share it would be wrong, since an invoice is not a user. A mixin lets both reuse one definition.

Form 1: an object copied onto the prototype

The simplest mixin is an object of methods copied with Object.assign.

assign-mixin.mjsJavaScript
const Serializable = {
  toJSON() {
    return { type: this.constructor.name, ...this };
  },
};

class User {
  constructor(name) {
    this.name = name;
  }
}
class Invoice {
  constructor(total) {
    this.total = total;
  }
}

Object.assign(User.prototype, Serializable);
Object.assign(Invoice.prototype, Serializable);

console.log(JSON.stringify(new User("Ada")));
console.log(JSON.stringify(new Invoice(40)));
Text
{"type":"User","name":"Ada"}
{"type":"Invoice","total":40}

The method is written once and reads the class name from this.constructor.name. Two things to know about Object.assign. It copies own enumerable properties, so a getter on the source is evaluated and copied as a plain value, not as a getter. And it replaces an existing method of the same name without warning, which matters in the pitfalls below.

Form 2: a function that returns a subclass

The second form is a function that takes a base class and returns a new class extending it. TypeScript's handbook documents this form, and it works well with super because the mixin sits in the real prototype chain.

subclass-mixin.mjsJavaScript
const Serializable = (Base) =>
  class extends Base {
    toJSON() {
      return { type: this.constructor.name, ...this };
    }
  };

const Timestamped = (Base) =>
  class extends Base {
    createdAt = "2026-11-20";
  };

class Entity {
  constructor(id) {
    this.id = id;
  }
}

class User extends Serializable(Timestamped(Entity)) {
  constructor(id, name) {
    super(id);
    this.name = name;
  }
}

const user = new User(1, "Ada");
console.log(JSON.stringify(user));
console.log(user instanceof Entity);
Text
{"type":"User","id":1,"createdAt":"2026-11-20","name":"Ada"}
true

Field order follows construction: Entity sets id, then Timestamped's field initializer adds createdAt, then User sets name. The type key comes first because toJSON writes it before spreading this. Each mixin call creates a new anonymous class in the chain, so the chain here is User then the Serializable class, then the Timestamped class, then Entity.

Calling super from a mixin

Because the subclass form is real inheritance, a mixin can extend a method of its base and call it.

super-mixin.mjsJavaScript
const Logged = (Base) =>
  class extends Base {
    save() {
      console.log(`saving ${this.constructor.name}`);
      return super.save();
    }
  };

class Repository {
  save() {
    return "saved";
  }
}

class UserRepository extends Logged(Repository) {}

console.log(new UserRepository().save());
Text
saving UserRepository
saved

The Object.assign form cannot do this. It copies a method onto the prototype and replaces whatever was there, so there is no super to call.

Combining mixins and order

Mixins apply from the inside out, so the last one wrapped is the first to run. When two of them override the same method, order decides which wins and whether the other is reached through super.

order.mjsJavaScript
const A = (Base) =>
  class extends Base {
    hello() {
      return `A(${super.hello()})`;
    }
  };

const B = (Base) =>
  class extends Base {
    hello() {
      return `B(${super.hello()})`;
    }
  };

class Root {
  hello() {
    return "root";
  }
}

console.log(new (A(B(Root)))().hello());
console.log(new (B(A(Root)))().hello());
Text
A(B(root))
B(A(root))

Each mixin wraps the result of the next one. When mixins interact like this, document the order they must be applied in.

Pitfall 1: silent collisions

Two mixins that define the same method name will override each other, and with Object.assign the later one wins with no message.

collision.mjsJavaScript
const Walker = {
  move() {
    return "walk";
  },
};
const Swimmer = {
  move() {
    return "swim";
  },
};

class Duck {}
Object.assign(Duck.prototype, Walker, Swimmer);

console.log(new Duck().move());
Text
swim

Walker.move is gone and nothing says so. A defensive helper can refuse to overwrite.

safe-mix.mjsJavaScript
function mixin(target, ...sources) {
  for (const source of sources) {
    for (const key of Object.keys(source)) {
      if (Object.hasOwn(target, key)) {
        throw new Error(`mixin collision on ${key}`);
      }
      target[key] = source[key];
    }
  }
  return target;
}

class Duck {}
try {
  mixin(Duck.prototype, Walker, Swimmer);
} catch (err) {
  console.log(err.message);
}
Text
mixin collision on move

The helper checks own properties of the target, so it catches a clash between two mixins applied in the same call, which is the case that goes wrong most often.

Pitfall 2: hidden dependencies

A mixin often assumes something about the class it joins. The Serializable mixin above assumes instances have only data worth serializing, and a mixin such as Comparable may assume a valueOf() method exists. Nothing in the language states this requirement. Write it down in a comment, and consider checking it.

requires.mjsJavaScript
const Comparable = (Base) =>
  class extends Base {
    constructor(...args) {
      super(...args);
      if (typeof this.valueOf !== "function" || this.valueOf === Object.prototype.valueOf) {
        throw new TypeError(`${this.constructor.name} must define valueOf`);
      }
    }
    compareTo(other) {
      return this.valueOf() - other.valueOf();
    }
  };

class Money extends Comparable(class {}) {
  constructor(cents) {
    super();
    this.cents = cents;
  }
  valueOf() {
    return this.cents;
  }
}

class Broken extends Comparable(class {}) {}

console.log(new Money(500).compareTo(new Money(200)));
try {
  new Broken();
} catch (err) {
  console.log(err.message);
}
Text
300
Broken must define valueOf

The check runs in the mixin's constructor, after super() has finished, at which point the subclass prototype is fully set up and valueOf is visible on this.

Pitfall 3: debugging

A prototype chain made of anonymous classes is hard to read in a stack trace. Naming the class inside the mixin helps.

named.mjsJavaScript
const Serializable = (Base) =>
  class Serializable extends Base {
    toJSON() {
      return { ...this };
    }
  };

class User extends Serializable(Object) {}
console.log(Object.getPrototypeOf(User.prototype).constructor.name);
Text
Serializable

A named class expression gives the chain a readable shape in debuggers and error messages.

Testing a mixin on its own

Test a mixin against a minimal base class defined inside the test, so a failure points at the mixin and not at a real entity.

mixin.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

test("Logged calls through to the base save", () => {
  class Base {
    save() {
      return "base";
    }
  }
  class Sample extends Logged(Base) {}
  assert.equal(new Sample().save(), "base");
});
Text
saving Sample
✔ Logged calls through to the base save (1.1ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

The first line comes from the console.log inside Logged.

When not to use mixins

If the behavior needs the object's internals or must be overridden carefully, composition is clearer: hold a collaborator in a field and delegate to it. Mixins also hide where a method comes from, which gets worse once a class has four or five of them. Use one or two small mixins for cross-cutting behavior such as serialization, events and logging, and prefer composition for anything that carries state or rules.

Mixins in the real world

Mixins appear throughout JavaScript, even where nobody calls them that. EventEmitter is the classic case: Node classes either extend it or copy its methods onto an object, and the second approach is a mixin. Many component libraries expose behavior such as dragging or selection as a function that takes a class and returns an extended one. In TypeScript, the handbook describes the subclass-factory form as the way to compose classes when you need more than single inheritance.

The strongest use case is a small, self-contained capability with no opinions about the host: serialization, an event system, a dispose method, timestamps. The weakest is a large behavior that touches the host's own state. When a mixin reads and writes fields it did not define, the host and the mixin become coupled in ways that no signature shows, and you are one rename away from a bug.

Alternatives worth weighing first

Before reaching for a mixin, consider three alternatives. A plain function that takes the object as an argument, such as toJson(entity), needs no inheritance and is trivially testable. Composition, where a class holds an emitter field and calls this.emitter.emit(...), makes the dependency visible and avoids method-name collisions entirely. And a shared base class is still correct when the classes really are variants of one thing. Mixins sit between these: they are the right tool when you want methods on the instance itself and the classes truly have no common ancestor.

One more detail concerns private fields. A class using #secret keeps it private to that class body, and a mixin cannot read it, which is the right outcome. If a mixin needs host data, define an explicit method the host must provide, as the Comparable example does with valueOf, so the contract is a visible part of the code and not a coincidence of property names.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.