JavaScriptFundamental (ES6), part 2
What a Proxy cannot intercept in JavaScript
63 What a Proxy cannot intercept
hardA proxy traps property operations, and nothing else. Prove it: put a bare proxy around a Map and call get on it; read a private field through a proxy of a class instance; then check what typeof and === report. Fix the Map case twice — once for its methods, once for size — and note what the fix costs.
Stuck? Three hints, smallest first
- 1. A
Mapkeeps its data in an internal slot, not in properties.Map.prototype.getlooks for that slot onthis. - 2. A method reached through a proxy is called with the proxy as
this. Bind it to the target instead — and remember an accessor has the same problem. - 3. There is no trap for
typeof, none for===, and a#fieldis not a property key.
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
const fares = new Map([['Yaba', 300], ['Ikeja', 500]]);
const bare = new Proxy(fares, {});
const slotError = attemptName(() => bare.get('Yaba'));
// The usual fix: hand back methods already bound to the target.
const bound = new Proxy(fares, {
get(t, key, receiver) {
const value = Reflect.get(t, key, receiver);
return typeof value === 'function' ? value.bind(t) : value;
},
});
const worksNow = bound.get('Yaba');
bound.set('Ojota', 250);
const targetChanged = fares.get('Ojota');
const identityLost = bound.get === bound.get;
const accessorStillFails = attemptName(() => bound.size); // size is a getter, not a method
// Forwarding the target as the RECEIVER too is what fixes the accessor.
const forwarded = new Proxy(fares, {
get(t, key) {
const value = Reflect.get(t, key, t);
return typeof value === 'function' ? value.bind(t) : value;
},
});
const sizeWorks = forwarded.size;
class Account {
#balance = 0;
constructor(name) { this.name = name; }
deposit(naira) { this.#balance += naira; return this.#balance; }
get balance() { return this.#balance; }
}
const account = new Account('Adaeze');
account.deposit(15000);
const proxied = new Proxy(account, {});
const privateError = attemptName(() => proxied.balance);
const publicFine = proxied.name;
const noSuchKey = [Object.getOwnPropertyNames(account), Object.keys(account)];
const identity = [proxied === account, bare === fares];
const typeofSays = [typeof new Proxy({}, {}), typeof new Proxy(function () {}, {})];
const stillAnInstance = [proxied instanceof Account, bare instanceof Map];
console.log('Map behind a bare proxy:', slotError, '| bound:', worksNow, '| size:', accessorStillFails);
console.log('private field :', privateError, '| public:', publicFine);
console.log('typeof :', typeofSays);
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('a Map method called through a bare proxy throws: the slot is not on the proxy', slotError, 'TypeError');
test('binding the method to the target fixes reads and writes', [worksNow, targetChanged], [300, 250]);
test('but size is a getter, not a method, so binding does nothing for it', accessorStillFails, 'TypeError');
test('forwarding the target as the receiver as well is what fixes the accessor', sizeWorks, 3);
test('and every read hands back a new bound function, so method identity breaks', identityLost, false);
test('a private field read through a proxy throws for the same reason a Map does', [privateError, publicFine], ['TypeError', 'Adaeze']);
test('a #field is not a property key, so nothing can list it or trap it', noSuchKey, [['name'], ['name']]);
test('identity cannot be trapped, and neither can typeof', [identity, typeofSays], [[false, false], ['object', 'function']]);
test('instanceof does work, because it goes through getPrototypeOf, which is a trap', stillAnInstance, [true, true]);
The mental model that fails here is "a proxy is a transparent wrapper". It is not: it is an object with the same property operations and a different identity. Anything the language does not express as a property operation goes straight past it.
Map, Set, Date, Promise, typed arrays and every private field are the cases you meet in practice, and they fail the same way. Map.prototype.get begins by checking that this has the [[MapData]] slot; the proxy is a different object and has no slots of its own, so it throws. A private #balance is worse: it is not keyed by name at all, so no trap could intercept it, and the sixth assertion shows it is invisible to getOwnPropertyNames as well.
The binding fix is incomplete, and the third assertion is where it shows. size is an accessor on Map.prototype, not a method, so there is nothing to hand back and bind — the getter runs during the read, against whatever receiver was passed. Forwarding Reflect.get(target, key, target) rather than the proxy fixes it, at the price exercise 64 warns about: an inherited getter now reads the target instead of the object the read started from.
The binding fix is also not free. Every read of bound.get allocates a new bound function, so method identity fails — removeEventListener with a handler read through such a proxy will not find it, and a WeakMap keyed on the method gets a fresh entry each time. Cache the bound methods if you need this in earnest. Binding also re-attaches this to the target, which means mutations you meant to observe now happen behind the proxy's back.
typeof, ===, Object.is and the internals of await's resolution are not property operations and have no traps. instanceof is the interesting exception: it reads the prototype, which is a property operation, so it works — and can be redirected, as exercise 67 does with Symbol.hasInstance.