← Back to JavaScript, page 7

javascript-0135 · Hard senior

What are mixins in JavaScript, how do you implement them, and what are the risks?

A mixin adds reusable behavior to a class without a single inheritance chain, because JavaScript classes can only extend one parent. Two common forms are copying methods onto a prototype with Object.assign and class factories (a function that takes a base class and returns a subclass). Risks include name collisions, hidden dependencies between mixins, and harder debugging, so keep mixins small and prefer composition when behavior is not truly shared.

Full answer

A class can extend only one parent. A mixin is a way to share behavior across unrelated classes without a deep hierarchy, such as adding serialize() or event methods to several classes.

Form 1, copying onto the prototype: Object.assign(User.prototype, canSerialize, canEmit). It is simple and works with plain objects, but copied methods are not on the prototype chain as classes, super inside them does not work as expected, and later changes to the mixin object are shared across all classes that got the same function references. Getters are evaluated during the copy by Object.assign, so use Object.defineProperties with descriptors for accessors.

Form 2, class factory (subclass factory): a function that takes a base class and returns a class that extends it. const Serializable = (Base) => class extends Base { serialize() {...} } Apply it by wrapping: class User extends Serializable(Person) {}, and combine several with Emitter(Serializable(Person)). Each application creates a new class in the chain, so super.method() works and the order is visible. Method resolution follows the chain, and the last mixin applied is closest to the instance.

Checks: instanceof does not know about a copied mixin. For factory mixins, you can add a Symbol.hasInstance check or a marker symbol, so hasMixin(obj, Serializable) works.

Risks and rules:

  • Name collisions: two mixins with the same method name silently override each other. Use clear names or symbols as keys.
  • Hidden coupling: a mixin that relies on fields of the host class breaks when those change. Document and check the requirements.
  • State: avoid mutable shared state in the mixin object, and initialize per-instance state in the constructor.
  • Debugging: long chains of anonymous classes produce confusing stack traces, so name the returned class.

Prefer composition (holding a helper object and delegating to it) when the behavior has its own state or the relationship is "has a", not "is a". Mixins fit small, stateless capabilities such as Comparable, Serializable, and event emitting.

javascript
// Form 1: copy methods onto a prototype
const canGreet = {
  greet() {
    return `Hi, I am ${this.name}`;
  },
};
class Person {
  constructor(name) {
    this.name = name;
  }
}
Object.assign(Person.prototype, canGreet);
console.log(new Person('Asha').greet());

// Form 2: class factories (subclass factories)
const Serializable = (Base) =>
  class Serializable extends Base {
    serialize() {
      return JSON.stringify(this);
    }
  };

const Timestamped = (Base) =>
  class Timestamped extends Base {
    createdAt = 'fixed-for-demo';
    describe() {
      return `${super.describe()} [created ${this.createdAt}]`;
    }
  };

class Entity {
  constructor(id) {
    this.id = id;
  }
  describe() {
    return `entity ${this.id}`;
  }
}

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

const product = new Product(7, 'Notebook');
console.log(product.serialize());
console.log(product.describe());
let proto = Object.getPrototypeOf(product);
const chain = [];
while (proto && proto !== Object.prototype) {
  chain.push(proto.constructor.name);
  proto = Object.getPrototypeOf(proto);
}
console.log('chain:', chain.join(' -> '));

// collisions: the mixin applied last wins
const A = (Base) => class extends Base { who() { return 'A'; } };
const B = (Base) => class extends Base { who() { return 'B'; } };
console.log(new (B(A(Object)))().who(), new (A(B(Object)))().who());

// detecting a mixin with a marker symbol
const isSerializable = Symbol('Serializable');
const Marked = (Base) => class extends Base { get [isSerializable]() { return true; } };
const hasMixin = (object, marker) => Boolean(object && object[marker]);
console.log(hasMixin(new (Marked(Entity))(1), isSerializable), hasMixin(new Entity(1), isSerializable));
console.log(product instanceof Entity, product instanceof Person);

Run with Node.js v24.22.1 as js-135.js; two runs gave identical output. Output: Hi, I am Asha {"id":7,"createdAt":"fixed-for-demo","title":"Notebook"} entity 7 [created fixed-for-demo] chain: Product -> Timestamped -> Serializable -> Entity B A true false true false

Key points

  • Mixins share behavior across classes despite single inheritance.
  • Object.assign onto a prototype is simple but copies by reference and does not support super or accessors well.
  • A class factory returns a subclass of the given base; it works with super and keeps a visible chain.
  • Risks: name collisions, hidden coupling, shared state, anonymous classes in stack traces.
  • Prefer composition for stateful or has-a relationships.

Common mistakes

  • Letting two mixins define the same method name without noticing.
  • Depending on fields of the host class inside the mixin without documenting it.
  • Putting mutable state on a shared mixin object.
  • Using mixins for a has-a relationship that composition expresses better.

Follow-ups

  • How do mixins compare with composition and with inheritance?
  • How does super work inside a class factory mixin?
  • How would you make instanceof work for a mixin?

Tips

  • Name both forms and say which you prefer: the class factory.
  • Show the collision rule: the last mixin applied wins.
  • End with when you would choose composition instead.