JavaScriptFundamental (ES6), part 2
Prototype methods vs per-instance fields in JavaScript
77 A prototype method is shared, a class field is not
hardGive a class one method and one arrow-function field that do the same thing. Compare them across two instances by identity, by Object.keys and through JSON.stringify. Then detach both and call them, and try to move each one with call.
Stuck? Three hints, smallest first
- 1. A method is defined once on the prototype. A field is assigned per instance, in the constructor.
- 2. An arrow captures
thiswhere it was created, socallhas nothing to change. - 3. A detached prototype method has
this === undefinedin a class body, which is always strict.
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
class Bus {
constructor(route) { this.route = route; }
label() { return 'bus to ' + this.route; } // on the prototype
labelArrow = () => 'bus to ' + this.route; // own property, per instance
}
const ojota = new Bus('Ojota');
const yaba = new Bus('Yaba');
const bothWork = [ojota.label(), ojota.labelArrow()];
const methodShared = ojota.label === yaba.label;
const fieldPerInstance = ojota.labelArrow === yaba.labelArrow;
const whereTheyLive = [
Object.hasOwn(ojota, 'label'),
Object.hasOwn(ojota, 'labelArrow'),
Object.hasOwn(Bus.prototype, 'label'),
];
const listed = [Object.keys(ojota), JSON.stringify(ojota)];
const moved = ojota.label.call(yaba);
const arrowRefusesToMove = ojota.labelArrow.call(yaba);
const boundCannotHelp = ojota.labelArrow.bind(yaba)();
const detachedMethod = ojota.label;
const detachedArrow = ojota.labelArrow;
const methodLostThis = attemptName(() => detachedMethod());
const arrowStillWorks = detachedArrow();
const rebound = detachedMethod.bind(ojota)();
console.log('shared, per instance:', methodShared, fieldPerInstance);
console.log('own keys :', listed);
console.log('call on each :', moved, '|', arrowRefusesToMove);
console.log('detached :', methodLostThis, '|', arrowStillWorks);
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.
test('both produce the same text, which is what hides the difference', bothWork, ['bus to Ojota', 'bus to Ojota']);
test('the method is one function shared by every instance', methodShared, true);
test('the field is a new function on each instance', fieldPerInstance, false);
test('so the field is an own property and the method is not', whereTheyLive, [false, true, true]);
test('which puts the field in Object.keys, ahead of route, though JSON drops functions', listed, [['labelArrow', 'route'], '{"route":"Ojota"}']);
test('call moves a prototype method to another instance', moved, 'bus to Yaba');
test('but the arrow captured this at construction, so call and bind cannot move it', [arrowRefusesToMove, boundCannotHelp], ['bus to Ojota', 'bus to Ojota']);
test('a detached method loses this and throws in strict mode', methodLostThis, 'TypeError');
test('while the detached arrow still works, and bind fixes the method', [arrowStillWorks, rebound], ['bus to Ojota', 'bus to Ojota']);
The two definitions read almost identically and are structurally opposite. label is created once, when the class is evaluated, and lives on Bus.prototype; every instance borrows it and supplies this at the call. labelArrow is an initialiser: it runs per construction, so a thousand buses allocate a thousand closures, each holding its own this.
That is the trade. The field is immune to detachment — the eighth and ninth assertions — which is why onClick={this.handleClick} works when handleClick is a field and throws when it is a method. The cost is memory, and something subtler: the seventh assertion shows call and bind being ignored. An arrow's this is lexical and permanent, so a field cannot be borrowed, cannot be tested against a stub receiver, and cannot be overridden by a subclass method of the same name in the usual way — the instance's own property always wins over the prototype's.
The fifth assertion is the one that surprises people in code review: class fields are enumerable own properties, so they show up in Object.keys, in spread and in for...in, right next to your data — and before it, because field initialisers run before the constructor body, which is also why a field cannot read a value the constructor has not assigned yet. JSON.stringify happens to drop them because functions do not serialise, but { ...bus } copies the closure and any snapshot-diffing code now sees a function among the fields.
The TypeError in the eighth assertion is not "undefined is not a function" — it is reading route off undefined. Class bodies are always strict, so a detached method's this is undefined rather than the global object, which is a mercy: the sloppy-mode version silently reads globalThis.route and returns 'bus to undefined'.