Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

call, apply and bind explained in JavaScript

80 Mixins, call, apply, bind, and the this that goes missing

hard

Compose behaviour without multiple inheritance: write mixins as functions from a base class to a subclass, stack two of them, and walk the resulting chain. Then borrow one of the methods for a plain object with call and apply, fix a receiver with bind, try to move a bound function, and detach a method to see it fail.

Stuck? Three hints, smallest first
  1. 1. A mixin is (Base) => class extends Base { ... }. Each application adds one link to the chain.
  2. 2. call and apply differ only in how the arguments arrive.
  3. 3. A bound function's this is final. A later call supplies arguments and nothing else.

The answer

const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };

class Party {
  constructor(name) { this.name = name; }
  describe() { return 'party ' + this.name; }
}

const Auditable = (Base) => class extends Base {
  audit(action) { return this.name + ' ' + action + ', logged'; }
};
const Payable = (Base) => class extends Base {
  pay(naira) { return this.name + ' paid ' + naira; }
};

const AuditableParty = Auditable(Party);
const PayableAuditableParty = Payable(AuditableParty);
class Vendor extends PayableAuditableParty {}

const vendor = new Vendor('Adaeze');
const bothBehaviours = [vendor.pay(45000), vendor.audit('restocked'), vendor.describe()];

const chain = [];
for (let link = Object.getPrototypeOf(vendor); link !== null; link = Object.getPrototypeOf(link)) {
  chain.push(
    link === Vendor.prototype ? 'Vendor'
      : link === PayableAuditableParty.prototype ? 'Payable'
      : link === AuditableParty.prototype ? 'Auditable'
      : link === Party.prototype ? 'Party'
      : 'Object.prototype'
  );
}
const instanceOfEach = [vendor instanceof Vendor, vendor instanceof AuditableParty, vendor instanceof Party];
const whereTheMethodsAre = [
  Object.getOwnPropertyNames(PayableAuditableParty.prototype),
  Object.getOwnPropertyNames(AuditableParty.prototype),
];

const borrower = { name: 'Chidi' };
const called = Vendor.prototype.pay.call(borrower, 5000);
const applied = Vendor.prototype.pay.apply(borrower, [5000]);

const bound = Vendor.prototype.pay.bind({ name: 'Ngozi' });
const boundCall = bound(7000);
const cannotRebind = bound.call({ name: 'somebody else' }, 7000);
const partiallyApplied = Vendor.prototype.pay.bind({ name: 'Ngozi' }, 7000)();
const boundLength = [bound.length, bound.name];

const detached = vendor.pay;
const lostThis = attemptName(() => detached(45000));
const fixedAgain = detached.bind(vendor)(45000);

console.log('both behaviours:', bothBehaviours);
console.log('chain          :', chain);
console.log('borrowed       :', called, '|', applied);
console.log('bound          :', boundCall, '| re-bound:', cannotRebind);

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 stacked mixins give the class every behaviour', bothBehaviours, ['Adaeze paid 45000', 'Adaeze restocked, logged', 'party Adaeze']);
test('each mixin is one real link in the chain, in application order', chain, ['Vendor', 'Payable', 'Auditable', 'Party', 'Object.prototype']);
test('so instanceof answers for every class you kept a reference to', instanceOfEach, [true, true, true]);
test('and each mixin owns only its own method', whereTheMethodsAre, [['constructor', 'pay'], ['constructor', 'audit']]);
test('call and apply borrow the method for any object of the right shape', [called, applied], ['Chidi paid 5000', 'Chidi paid 5000']);
test('bind fixes this permanently: a later call cannot move it', [boundCall, cannotRebind], ['Ngozi paid 7000', 'Ngozi paid 7000']);
test('bind also fixes leading arguments, which is partial application', partiallyApplied, 'Ngozi paid 7000');
test('and the bound function reports the arity left and a bound name', boundLength, [1, 'bound pay']);
test('a detached method loses this and throws, and bind is what puts it back', [lostThis, fixedAgain], ['TypeError', 'Adaeze paid 45000']);

A mixin is a function from a class to a class, and that is the whole trick: Payable(Auditable(Party)) builds a genuine chain rather than merging bags of methods. The second assertion is why this beats Object.assign(Class.prototype, methods) — each behaviour is a distinct link, so super works inside a mixin, an override resolves in the usual order, and instanceof answers for any layer you kept a reference to.

The cost is the reference. Payable(Auditable(Party)) produces anonymous classes, so unless you name them on the way up, as here, there is nothing to test with instanceof and stack traces are unhelpful. Applying the same mixin to two bases also produces two unrelated classes, which is the usual reason a mixin-heavy codebase ends up caching them.

call, apply and bind are the manual controls for the same this the chain supplies automatically. call and apply differ only in argument shape — spread has made apply mostly redundant — and both let a method be borrowed by any object with the right fields, which is how Array.prototype.slice.call(arguments) worked for a decade. bind is different in kind: it returns a new function whose receiver is final, which the sixth assertion proves by trying to override it and failing. Note the arity in the eighth assertion: binding an argument reduces length, and the name gains a bound prefix, both of which matter if anything inspects your functions.

The last assertion is the one to carry around. const detached = vendor.pay copies the function and nothing else — the receiver was never part of it, it comes from the call site. Passing a method as a callback is exactly that copy, which is why setTimeout(vendor.pay, 0) throws while setTimeout(() => vendor.pay(45000), 0) does not, and why bind or an arrow wrapper is the fix.

Newsletter

New writing, when it lands.

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