JavaScriptFundamental (ES6), part 1
Prototype method vs arrow function field in JavaScript
50 A prototype method against a field holding an arrow
fairGive a counter both a normal method and a field holding an arrow function. Detach each from the instance and call it. Then show that the own field shadows a subclass method of the same name.
Stuck? Three hints, smallest first
- 1. A method is on the prototype and gets its
thisfrom the call site, so a detached reference has none. - 2. An arrow in a field captures
thiswhen the instance is built, so it survives detachment. - 3. Own properties are found before prototype ones, and a field is an own property.
class Counter {
count = 0;
bump() { // prototype method
this.count++;
return this.count;
}
bumpArrow = () => { // own field, this captured
this.count++;
return this.count;
};
}
class Sub extends Counter {
bumpArrow() { // never reached
return 'from the subclass prototype';
}
}
const attempt = (fn) => { try { return fn(); } catch (e) { return e.constructor.name; } };
const counter = new Counter();
const detachedMethod = counter.bump;
const detachedArrow = counter.bumpArrow;
const rebound = counter.bump.bind(counter);
const looseCall = attempt(() => detachedMethod());
console.log('detached method:', looseCall);
console.log('own keys :', Object.keys(counter));
console.log('arrow on prototype?', Object.prototype.hasOwnProperty.call(Counter.prototype, 'bumpArrow'));
console.log('subclass call :', new Sub().bumpArrow(), '<- the inherited field won');
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('called on the instance, both forms work', [counter.bump(), counter.bumpArrow()], [1, 2]);
test('detached, the prototype method has no this and throws in strict mode', looseCall, 'TypeError');
test('the arrow field kept the this it captured', detachedArrow(), 3);
test('bind repairs the prototype method', rebound(), 4);
test('the arrow is an own property; the method is not', Object.keys(counter), ['count', 'bumpArrow']);
test('nor is the arrow on the prototype', Object.prototype.hasOwnProperty.call(Counter.prototype, 'bumpArrow'), false);
test('every instance shares one prototype method', new Counter().bump === counter.bump, true);
test('but each gets its own arrow', new Counter().bumpArrow === counter.bumpArrow, false);
test('and the inherited own field shadows the subclass method of the same name', new Sub().bumpArrow(), 1);
A field holding an arrow is the standard answer to "my callback lost this": pass obj.bumpArrow to setTimeout or an event listener and it still works, where obj.bump would throw. The cost is in the seventh and eighth assertions — one function per instance instead of one per class — which matters when the instances are thousands of list rows and not one counter.
The last assertion is the trap. Counter's field initialiser installs an own bumpArrow on every instance, including instances of Sub, and own properties are found before prototype ones. So Sub's method is unreachable: the override silently does nothing, with no error to tell you. If a member is meant to be overridable, write it as a method.