Sub topic 16
Composing Behavior with Mixins
This chapter assumes you already know how extends and super work, how the prototype chain resolves method lookups, and how instanceof checks it. It shows how to add reusable behavior to a class without forcing every class into a single inheritance tree.
The Problem: One Parent per Class
A JavaScript class can extend only one parent. The extends clause accepts a single expression, and each object has exactly one [[Prototype]]. That works until two unrelated features need to be shared by unrelated classes. For example, User and Invoice may both need to be serializable, and User and Comment may both need timestamps. A single base class that bundles all of these ends up giving every subclass behavior it never asked for.
A mixin is a function that takes a base class and returns a new class that extends it. Because extends accepts any expression that evaluates to a constructor, the function can build that subclass on demand:
const Serializable = (Base) => class Serializable extends Base {
serialize() {
return JSON.stringify(this);
}
};
class User {
constructor(name) {
this.name = name;
}
}
class SerializableUser extends Serializable(User) {}
console.log(new SerializableUser('Ada').serialize()); // '{"name":"Ada"}'Serializable(User) runs first and returns a class whose parent is User. SerializableUser then extends that returned class. No special language feature is involved beyond class expressions and ordinary single inheritance.
Stacking Several Mixins
Mixins compose by nesting calls. Each call inserts one more class into the chain:
const Serializable = (Base) => class Serializable extends Base {
serialize() {
return JSON.stringify(this);
}
};
const Timestamped = (Base) => class Timestamped extends Base {
constructor(...args) {
super(...args);
this.createdAt = Date.now();
}
};
class User {
constructor(name) {
this.name = name;
}
}
class AppUser extends Timestamped(Serializable(User)) {}
const u = new AppUser('Ada');
console.log(u.name); // 'Ada'
console.log(typeof u.createdAt); // 'number'
console.log(u.serialize().includes('"createdAt"')); // trueThe constructor in Timestamped takes ...args and forwards them unchanged. A mixin does not know which base it will be applied to, so it must not assume a particular constructor signature. If a mixin needs its own options, a common approach is to read them from a single options object that the whole chain shares, instead of adding positional parameters.
Because the result is a plain prototype chain, the usual lookup rules apply. The outermost mixin sits closest to the instance, so its methods win when two mixins define the same name.
Cooperative Methods with super
Inside a mixin, super refers to whatever base the mixin was applied to. That lets several mixins each add a piece to the same method:
class User {
constructor(name) {
this.name = name;
}
describe() {
return `User ${this.name}`;
}
}
const Admin = (Base) => class Admin extends Base {
describe() {
return `${super.describe()} [admin]`;
}
};
const Verified = (Base) => class Verified extends Base {
describe() {
const base = typeof super.describe === 'function' ? super.describe() : '';
return `${base} [verified]`.trim();
}
};
class SuperUser extends Verified(Admin(User)) {}
class Guest extends Verified(class {}) {}
console.log(new SuperUser('Ada').describe()); // 'User Ada [admin] [verified]'
console.log(new Guest().describe()); // '[verified]'Admin assumes its base has describe(), and it throws a TypeError if the base does not. Verified checks first, so it works on any base. Decide for each mixin whether it requires a method from the base or treats the method as optional, and write that down in its documentation.
Edge Cases and Gotchas
Order Changes Behavior
Verified(Admin(User)) and Admin(Verified(User)) produce different strings, 'User Ada [admin] [verified]' versus 'User Ada [verified] [admin]'. When mixins override the same method or set the same property, application order is part of the class's meaning. Keep the order the same across the codebase.
instanceof Does Not Work on the Mixin Function
Each call to Serializable(Base) creates a brand-new class. obj instanceof Serializable checks the arrow function's prototype property, and arrow functions have none, so the check throws a TypeError. You can define Symbol.hasInstance on the mixin function, which instanceof consults before anything else:
const isSerializable = Symbol('Serializable');
const Serializable = (Base) => {
class Serializable extends Base {
serialize() {
return JSON.stringify(this);
}
}
Serializable.prototype[isSerializable] = true;
return Serializable;
};
Object.defineProperty(Serializable, Symbol.hasInstance, {
value: (obj) => obj?.[isSerializable] === true,
});
class Note {}
class SavedNote extends Serializable(Note) {}
console.log(new SavedNote() instanceof Serializable); // true
console.log(new Note() instanceof Serializable); // false
console.log(42 instanceof Serializable); // falseThe optional chaining obj?.[isSerializable] keeps null and undefined from throwing. Using a symbol keeps the brand off JSON.stringify output and away from string-keyed properties.
Private Fields Are Per Application
A #field declared inside a mixin is a new private name every time the mixin function runs. Two classes built from the same mixin cannot read each other's private fields, and a #field in obj check written inside one application returns false for instances of another. Usually this is what you want. It matters when a static helper or a comparison method needs to accept instances from several mixed classes.
Duplicate Applications
Applying the same mixin twice, as in Serializable(Serializable(User)), adds two classes to the chain and runs any constructor logic twice. Applying it to the same base in two modules creates two unrelated classes. If that is a problem, cache results in a WeakMap keyed by Base and return the cached class on repeat calls. You can also have the mixin check Base.prototype[isSerializable] and return Base unchanged when it is already present.
Copy-Based Mixins Are Weaker
An older pattern copies methods onto a prototype with Object.assign(User.prototype, serializableMethods). It avoids the extra chain links, but the copied methods cannot use super, since super is bound to the object a method was defined on. Object.assign also calls getters and copies the resulting values instead of the accessors. Collisions overwrite existing methods without any warning. Prefer the class-expression form unless you need to patch a class you cannot change.
Choosing Between Mixins, Inheritance, and Composition
| Approach | Use when | Main cost |
|---|---|---|
| `extends` a single parent | The subclass really is a specialized kind of the parent | One parent only, and deep trees become rigid |
| Class-expression mixin | Several unrelated classes need the same behavior on `this`, possibly cooperating via `super` | Longer chains, order sensitivity, name collisions |
| Composition (store a helper object in a field) | The behavior can live in a separate object, such as a logger or serializer | Requires forwarding calls, as in `this.serializer.serialize(this)` |
A good rule of thumb is to try composition first. It keeps state separate and makes collisions impossible. Reach for a mixin when the behavior has to look like a method of the object itself, or has to override and extend that object's existing methods.
Exercise
Write a mixin Comparable that adds a compareTo(other) method, returning -1, 0, or 1 based on a value getter defined by the base class. Apply it to a Price class whose value getter returns this.cents, and show what new Price(500).compareTo(new Price(300)) returns.
Show answer
const Comparable = (Base) => class Comparable extends Base { compareTo(other) { return Math.sign(this.value - other.value); } }; class PriceBase { constructor(cents) { this.cents = cents; } get value() { return this.cents; } } class Price extends Comparable(PriceBase) {} The call returns 1, because 500 - 300 is positive. compareTo finds the value getter through the prototype chain at PriceBase.prototype.
Exercise
Given class A extends Logged(Cached(Base)) {}, where both mixins override fetch() and call super.fetch(), which mixin's fetch() runs first when you call new A().fetch(), and why?
Show answer
Logged's fetch() runs first. Logged(...) is the outermost call, so its class sits directly above A.prototype in the chain and method lookup finds it first. Its super.fetch() then reaches Cached's fetch(), which in turn calls Base's fetch().