Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Mixins with composition and class factories in JavaScript

135 mixins, by object composition and by subclass factory

hard

Build a driver object by spreading together three small feature makers that share one closed-over state object, so no this is involved anywhere. Show that a method pulled off the object still works, where a class method pulled off its instance does not. Then do the same job the other way — a mixin as a function from a base class to a subclass — and find the collision that object spreading hides.

Stuck? Three hints, smallest first
  1. 1. Each maker takes state and returns an object of functions closed over it. The composed object is just { ...a(state), ...b(state) }.
  2. 2. Because the functions never mention this, destructuring one off the object cannot break it. That is the whole advantage.
  3. 3. A class mixin is const M = (Base) => class extends Base { ... }, and they nest: class X extends M(N(Base)) {}.

The answer

const canGreet = (state) => ({
  greet: () => `Kaabo, ${state.name}`,
});

const canBill = (state) => ({
  bill: (km) => state.rate * km,
  raise: (by) => { state.rate += by; return state.rate; },
});

const canLog = (state) => ({
  log: (line) => { state.entries = [...state.entries, line]; return state.entries.length; },
  history: () => [...state.entries],
});

const makeDriver = ({ name, rate }) => {
  const state = { name, rate, entries: [] };
  return {
    ...canGreet(state),
    ...canBill(state),
    ...canLog(state),
    snapshot: () => ({ ...state }),
  };
};

const alsoGreets = () => ({ greet: () => 'a different greeting' });
const clashed = { ...canGreet({ name: 'Ada' }), ...alsoGreets() };

const Timestamped = (Base) => class extends Base {
  stamp(n) { return `${this.constructor.name}#${n}`; }
};
const Countable = (Base) => class extends Base {
  static tally(list) { return list.length; }
};
class Person {
  constructor(name) { this.name = name; }
}
class Rider extends Timestamped(Countable(Person)) {}

class ClassDriver {
  constructor(rate) { this.rate = rate; }
  bill(km) { return this.rate * km; }
}

const driver = makeDriver({ name: 'Musa Bello', rate: 15000 });
const beforeRaise = driver.bill(2);
const newRate = driver.raise(1000);
const afterRaise = driver.bill(2);
const logged = [driver.log('Yaba to Ojota'), driver.log('Ojota to Ketu')];
const { bill } = driver;
const detached = bill(3);

const loose = new ClassDriver(15000).bill;
let looseError = 'no error';
try { loose(3); } catch (e) { looseError = e.constructor.name; }

const rider = new Rider('Ngozi');

console.log('driver  :', driver.greet(), '|', driver.snapshot());
console.log('detached:', detached, '| class method detached:', looseError);
console.log('mixins  :', rider.stamp(3), Rider.tally([1, 2]), rider instanceof Person);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the makers compose into one object with all the features', Object.keys(driver), ['greet', 'bill', 'raise', 'log', 'history', 'snapshot']);
test('and they share one state, so a raise changes what billing sees', [beforeRaise, newRate, afterRaise], [30000, 16000, 32000]);
test('the greeting reads the same state object', driver.greet(), 'Kaabo, Musa Bello');
test('logging accumulates, and history hands back a copy', [logged, driver.history()], [[1, 2], ['Yaba to Ojota', 'Ojota to Ketu']]);
test('a method taken off the object still works: state came from a closure', detached, 48000);
test('the same move on a class method loses this under strict mode', looseError, 'TypeError');
test('spreading is last-wins, and a name collision is completely silent', clashed.greet(), 'a different greeting');
test('a class mixin stacks methods and statics onto a base', [rider.stamp(3), Rider.tally([1, 2])], ['Rider#3', 2]);
test('and the instance is still the base type, so instanceof survives', [rider instanceof Person, rider.name], [true, 'Ngozi']);

Two techniques, one goal: features assembled rather than inherited. Object composition keeps state in a closure and never mentions this, which is why the fifth and sixth assertions differ — const { bill } = driver works, while the same destructuring of a class method gives you a function whose this is undefined and a TypeError on the first property read. Anywhere a method is passed as a callback, that difference is the bug you were going to have.

The cost is real and measurable: every instance carries its own set of closures instead of sharing one prototype. For a handful of objects that is nothing; for a hundred thousand it is memory you can see. Classes pay the opposite trade — one shared prototype, plus the this fragility.

The subclass-factory mixin keeps the prototype chain, so instanceof still works and statics come along too, at the price of a longer chain and stacking order that matters. And the seventh assertion is the hazard both styles share: two mixins defining greet means the later one wins with no warning at all. Keep mixin surfaces small and names specific, or check for collisions when you compose.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.