JavaScriptFundamental (ES6), part 2
Reflect and the receiver argument in JavaScript
64 Reflect, and the receiver argument that matters
fairReflect is the plain-function form of every operation a trap can intercept. Use Reflect.get and Reflect.set with an explicit receiver to run a getter against a different object, list a symbol and a non-enumerable key with Reflect.ownKeys, and compare how Reflect and Object report a refusal.
Stuck? Three hints, smallest first
- 1. The third argument to
Reflect.getbecomesthisinside a getter. - 2.
Reflect.set(target, key, value, receiver)writes onto the receiver, not the target. - 3.
Object.definePropertythrows whereReflect.definePropertyreturnsfalse.
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
const stallPrototype = {
get label() { return this.item + ' by the ' + this.unit; },
};
const yam = { item: 'yam', unit: 'tuber' };
const rice = Object.create(stallPrototype);
rice.item = 'rice';
rice.unit = 'kg';
const own = Reflect.get(rice, 'item');
const throughChain = Reflect.get(rice, 'label');
const withOtherReceiver = Reflect.get(stallPrototype, 'label', yam);
const source = { fare: 400 };
const receiver = {};
const setReported = Reflect.set(source, 'fare', 450, receiver);
const whereItLanded = [source.fare, receiver.fare];
const AUDIT = Symbol('audit');
const order = { customer: 'Bisi', [AUDIT]: 'Balogun till 3' };
Object.defineProperty(order, 'internalRef', { value: 'LAG-0064', enumerable: false });
const objectKeys = Object.keys(order);
const allKeys = Reflect.ownKeys(order).map(String);
const names = Object.getOwnPropertyNames(order);
const frozen = Object.freeze({ fare: 400 });
const reflectRefuses = Reflect.defineProperty(frozen, 'fare', { value: 500 });
const objectThrows = attemptName(() => Object.defineProperty(frozen, 'fare', { value: 500 }));
const deleteRefuses = Reflect.deleteProperty(frozen, 'fare');
const deleteThrows = attemptName(() => { delete frozen.fare; });
const hasAgrees = [Reflect.has(rice, 'label'), 'label' in rice, Reflect.has(rice, 'zone')];
console.log('getter with another receiver:', withOtherReceiver);
console.log('set landed on :', whereItLanded);
console.log('keys :', objectKeys, 'vs', allKeys);
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('Reflect.get with no receiver is ordinary property access', [own, throughChain], ['rice', 'rice by the kg']);
test('a receiver runs the inherited getter against a different object', withOtherReceiver, 'yam by the tuber');
test('Reflect.set reports success and writes onto the receiver', [setReported, whereItLanded], [true, [400, 450]]);
test('Object.keys hides both the symbol and the non-enumerable key', objectKeys, ['customer']);
test('Reflect.ownKeys hides neither', allKeys, ['customer', 'internalRef', 'Symbol(audit)']);
test('getOwnPropertyNames sees the non-enumerable one but never symbols', names, ['customer', 'internalRef']);
test('Reflect reports a refused define or delete as false', [reflectRefuses, deleteRefuses], [false, false]);
test('where the Object form and the delete operator throw in strict mode', [objectThrows, deleteThrows], ['TypeError', 'TypeError']);
test('Reflect.has is exactly the `in` operator, chain included', hasAgrees, [true, true, false]);
Reflect exists so a trap can do its default job. Every method matches a trap one-for-one and takes the arguments the trap receives, which is why forwarding is Reflect.get(target, key, receiver) and not target[key].
The receiver is the argument people drop, and the second assertion is what it costs. A getter on the prototype reads this.item, so this has to be the object the read started from. Forward without the receiver and the getter runs against the target instead — on a proxy that means every inherited getter and setter silently reads and writes the wrong object, a bug that only appears once someone adds a getter to the class.
The third assertion shows the same idea for writes: Reflect.set with a receiver leaves the source at 400 and creates fare on the receiver. That is exactly how assigning to an inherited data property behaves — the write lands on the instance, not the prototype — and Reflect.set is the only way to say it out loud.
The other half of Reflect is tone. Object.defineProperty and delete announce refusal by throwing, which forces a try around a question you only wanted answered; Reflect.defineProperty and Reflect.deleteProperty return false. Neither is more correct, but returning a boolean composes, and it is the form a trap must return anyway.