Sub topic 20
Sharing Behavior with Mixins and Composition
This chapter assumes you already know how class, extends, and super map onto prototype links, and that you can tell own properties from inherited ones with Object.hasOwn. Every example runs as written in Node.js or a browser console.
Single inheritance gives each object one prototype chain. Real code often needs behavior that cuts across that chain. A Point, a User, and an Invoice might all need to serialize themselves, but they have no sensible common parent. If you force them under a shared Serializable base class, the hierarchy starts describing your plumbing instead of your domain. This chapter covers three tools for that problem: copy-based mixins, subclass-factory mixins, and plain composition.
Copy-Based Mixins with Object.assign
The simplest mixin is an object of methods copied onto a prototype:
const Serializable = {
toJSONString() {
return JSON.stringify(this);
}
};
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
Object.assign(Point.prototype, Serializable);
const p = new Point(1, 2);
console.log(p.toJSONString()); // '{"x":1,"y":2}'
console.log(Object.hasOwn(p, 'toJSONString')); // falseThe method lives on Point.prototype, so all instances share it and lookup works the usual way. Because this is bound at call time, the copied method serializes the instance and not the Serializable object.
This adds no level to the chain. Object.getPrototypeOf(Point.prototype) is still Object.prototype. That keeps things simple, and it also produces most of the gotchas below.
Gotcha: Object.assign Copies Values, Not Accessors
Object.assign reads each enumerable own property from the source with an ordinary get, then writes it to the target with an ordinary set. A getter on the mixin therefore runs once, against the mixin object, at copy time:
const Sized = {
get size() {
return this.items.length;
}
};
class Bag {
constructor() {
this.items = [];
}
}
try {
Object.assign(Bag.prototype, Sized);
} catch (err) {
console.log(err instanceof TypeError); // true: this.items is undefined on Sized
}
// Copy property descriptors instead, so the getter itself is transferred
Object.defineProperties(Bag.prototype, Object.getOwnPropertyDescriptors(Sized));
const bag = new Bag();
bag.items.push('a', 'b');
console.log(bag.size); // 2If a mixin contains getters, setters, or non-enumerable members, copy descriptors with Object.getOwnPropertyDescriptors and Object.defineProperties.
Gotcha: Name Collisions Are Silent
With Object.assign, the last write wins. If two mixins both define init, or a mixin defines a method the class already has, one version disappears without any warning. A defensive helper can check for this first:
function mixInto(target, ...sources) {
for (const source of sources) {
for (const key of Reflect.ownKeys(source)) {
if (key in target) {
throw new Error(`Mixin conflict on "${String(key)}"`);
}
}
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
}
return target;
}
class Thing {}
mixInto(Thing.prototype, { a() { return 1; } });
try {
mixInto(Thing.prototype, { a() { return 2; } });
} catch (err) {
console.log(err.message); // 'Mixin conflict on "a"'
}Gotcha: No Identity and a Frozen super
Copied methods leave no trace that instanceof can see. p instanceof Serializable throws a TypeError, because Serializable is not callable. A method that uses super keeps the home object it was defined on. super inside a copied method still resolves against the original mixin literal's prototype, not the class it was copied into.
Subclass-Factory Mixins
A subclass factory is a function that takes a base class and returns a new class extending it. Each mixin becomes a real link in the prototype chain:
const Serializable = (Base) => class extends Base {
toJSONString() {
return JSON.stringify(this);
}
};
const Timestamped = (Base) => class extends Base {
constructor(...args) {
super(...args);
this.createdAt = 0; // fixed value so the output is predictable
}
describe() {
const base = super.describe ? super.describe() : '';
return `${base} @${this.createdAt}`.trim();
}
};
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
describe() {
return `(${this.x}, ${this.y})`;
}
}
class SmartPoint extends Timestamped(Serializable(Point)) {}
const sp = new SmartPoint(1, 2);
console.log(sp.toJSONString()); // '{"x":1,"y":2,"createdAt":0}'
console.log(sp.describe()); // '(1, 2) @0'
console.log(sp instanceof Point); // trueBecause every mixin is a genuine subclass, super works, constructors chain, and overrides layer in a predictable order. Mixins applied later sit closer to the instance and win.
The cost is depth. Each application adds an anonymous prototype, which makes stack traces and debugger views longer. Each call to Serializable(Base) also produces a new class, so there is no single Serializable constructor to use with instanceof. If you need that check, use a Symbol brand. Each mixin sets a symbol-keyed property on its prototype, and the check tests for that symbol.
Composition: Has-a Instead of Is-a
Often the cleanest answer involves no inheritance at all. The object holds a collaborator and delegates to it:
class MemoryLogger {
constructor() {
this.lines = [];
}
log(message) {
this.lines.push(message);
}
}
class Order {
constructor(id, logger) {
this.id = id;
this.logger = logger;
}
place() {
this.logger.log(`Order ${this.id} placed`);
return true;
}
}
const logger = new MemoryLogger();
const order = new Order(42, logger);
order.place();
console.log(logger.lines); // ['Order 42 placed']Order never inherits logging. It can swap in a different logger at runtime or in tests, and its prototype chain stays a single level. The trade-off is explicit wiring: you pass dependencies in and write forwarding calls yourself.
Choosing an Approach
| Approach | Chain depth | `super` works | Conflicts | Best for |
|---|---|---|---|---|
| `Object.assign` mixin | unchanged | no | silent overwrite | small, self-contained method bundles |
| Descriptor-copy mixin | unchanged | no | detectable with a check | mixins with getters or setters |
| Subclass factory | +1 per mixin | yes | ordered overriding | behavior that needs constructors or `super` |
| Composition | unchanged | not applicable | none | swappable or testable collaborators |
Exercise
You run Object.assign(Widget.prototype, { get label() { return this.name.toUpperCase(); } }) and get a TypeError before any Widget exists. Why does this happen, and how do you fix it?
Show answer
Object.assign calls the getter at copy time with this set to the mixin literal. The literal has no name property, so this.name is undefined and toUpperCase throws. Copy the accessor itself instead: Object.defineProperties(Widget.prototype, Object.getOwnPropertyDescriptors(mixin)).
Exercise
Given class C extends A(B(Base)) {}, where both mixins A and B define greet() and call super.greet(), in what order do the greet bodies run when you call new C().greet(), and which body finishes last?
Show answer
Lookup finds A's greet first because A is closest to C. A calls super.greet(), which runs B's greet, which calls Base's greet. The bodies start in the order A, B, Base and finish in the order Base, B, A, so A's code after its super call runs last.
Exercise
Why does instanceof not work for checking whether an object uses a copy-based mixin, and what can you use instead?
Show answer
A copy-based mixin is a plain object that never becomes part of the prototype chain, and instanceof needs a callable right-hand side with a prototype property found on the chain. Instead, check for the method you need (typeof obj.toJSONString === 'function') or add a Symbol brand to the mixin and test for it with the in operator.