Sub topic 16
Composing Behavior with Mixins
This chapter assumes you already know class expressions, extends, and super from earlier chapters, and that you are comfortable with arrow functions.
JavaScript classes support only single inheritance, so a class can have exactly one parent. Sometimes you need to share a piece of behavior, such as serialization or logging, across classes that have no common ancestor. A mixin solves this. A mixin is a function that takes a base class and returns a new class that extends it.
The Basic Pattern
extends accepts any expression that evaluates to a constructor, including a function call. That is why the pattern works.
const Serializable = (Base) => class 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) builds an anonymous class whose parent is User. Then SerializableUser extends that anonymous class. No special language feature is involved. The mixin is a plain function that returns a class expression.
Stacking Mixins
You can nest mixin calls. Each call adds one more link to the prototype chain, and super inside each mixin refers to whatever class sits below it.
const Polite = (Base) => class extends Base {
describe() {
return `Please meet ${super.describe()}`;
}
};
const Loud = (Base) => class extends Base {
describe() {
return super.describe().toUpperCase();
}
};
class User {
constructor(name) {
this.name = name;
}
describe() {
return this.name;
}
}
class Guest extends Loud(Polite(User)) {}
console.log(new Guest('Ada').describe()); // 'PLEASE MEET ADA'The outermost mixin sits closest to the subclass, so its method runs first. Loud calls super.describe(), which reaches Polite, which in turn calls User.
Mixins with Constructors
If a mixin defines a constructor, it must forward its arguments to super, because the mixin cannot know what the base constructor expects.
const Tagged = (Base) => class extends Base {
constructor(...args) {
super(...args);
this.tags = [];
}
tag(label) {
this.tags.push(label);
return this;
}
};
class Item {
constructor(title) {
this.title = title;
}
}
class TaggedItem extends Tagged(Item) {}
const item = new TaggedItem('Lamp').tag('home').tag('sale');
console.log(item.title, item.tags); // 'Lamp' [ 'home', 'sale' ]Common Errors
| Problem | Cause | Fix |
|---|---|---|
| `TypeError: (intermediate value).describe is not a function` | The mixin calls `super.describe()`, but the base class has no such method | Document what the mixin requires, or use `super.describe?.()` |
| Base constructor receives `undefined` | The mixin constructor calls `super()` without arguments | Use `constructor(...args) { super(...args); }` |
| `obj instanceof Serializable` throws | `Serializable` is an arrow function with no `prototype`, so it is not a class | Check for the method itself, or keep a brand such as a `Symbol` |
| Silent overwrites | Two mixins define the same method or field name | Choose distinct names, or call `super` in each method on purpose |
Exercise
Given the Polite and Loud mixins above, what does new (Polite(Loud(User)))('Ada').describe() return, and why does it differ from the Guest example?
Show answer
It returns 'Please meet ADA'. Polite is now the outermost mixin, so it runs first and calls super.describe(), which reaches Loud. Loud uppercases only User's result, 'Ada', giving 'ADA'. Polite then adds its prefix to that.
Exercise
Write a mixin Countable that adds a count instance field starting at 0 and an increment() method that returns this. Apply it to an empty class Base.
Show answer
const Countable = (B) => class extends B { count = 0; increment() { this.count++; return this; } }; class Base {} class Counter extends Countable(Base) {} console.log(new Counter().increment().increment().count); // 2