Sub topic 4
Intercepting Reads and Writes with get and set
This chapter assumes you know how to create a proxy from a target and a handler, and that you know a trap is a handler method that maps to an internal method. It also assumes you are comfortable with property access, this, and strict mode.
The get and set traps are the ones you will write most often. get intercepts the internal method [[Get]], which runs on every property read. set intercepts [[Set]], which runs on every property assignment.
The get Trap
The engine calls get(target, prop, receiver) whenever code reads a property through the proxy:
targetis the wrapped object.propis the property key. It is a string or a symbol.receiveris the object the read started on. That is usually the proxy itself.
The trap's return value becomes the result of the read.
const target = { greeting: 'hello' };
const handler = {
get(target, prop, receiver) {
console.log(`get ${String(prop)}`);
return Reflect.get(target, prop, receiver);
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.greeting); // logs "get greeting", then "hello"Reflect.get performs the default read. The next chapter covers it fully. For now, treat it as "do what would have happened without the proxy."
The trap fires for more than dot access. proxy['greeting'], destructuring (const { greeting } = proxy), and reads made by built-ins such as JSON.stringify all go through [[Get]]. They all reach your trap.
The set Trap
The engine calls set(target, prop, value, receiver) on assignment. The trap must return a boolean. true means the write succeeded.
const person = new Proxy({}, {
set(target, prop, value, receiver) {
if (prop === 'age' && (!Number.isInteger(value) || value < 0)) {
throw new TypeError('age must be a non-negative integer');
}
return Reflect.set(target, prop, value, receiver);
}
});
person.age = 30; // stored
person.age = -1; // throws TypeErrorReflect.set returns the boolean you need, so returning its result is the simplest correct choice.
Common Errors
Returning false (or nothing) from set
If set returns a falsy value, the assignment fails. In strict mode, which includes modules and class bodies, a failed assignment throws a TypeError. In sloppy mode it fails silently. Leaving out the return statement is the same as returning undefined.
'use strict';
const readOnly = new Proxy({ x: 1 }, {
set() {
return false;
}
});
try {
readOnly.x = 2;
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(readOnly.x); // 1Interpolating a symbol key
prop can be a symbol, such as Symbol.iterator or Symbol.toPrimitive. The engine reads these keys when you spread an object or log it. Putting a symbol into a template literal throws a TypeError, so wrap the key in String(prop) before you log it.
Recursing through the proxy
If you read receiver[prop] or proxy[prop] inside the get trap, the read goes through the proxy again and triggers the trap again. It recurses until the stack overflows. Inside a trap, operate on target or call Reflect.
Expecting the trap to see the target directly
The traps fire only for operations on the proxy. Code that holds a reference to the original target bypasses them completely. If validation matters, give callers only the proxy.
Exercise
In a module, a proxy has the handler { set(t, p, v) { if (typeof v === 'string') { t[p] = v; } } }. What happens when you run proxy.name = 'Ada', and why?
Show answer
The value is written to the target, but the trap returns undefined, which counts as failure. Modules run in strict mode, so the assignment then throws a TypeError. Fix it by returning true after the write, or by returning Reflect.set(t, p, v).
Exercise
Write a get trap that returns the string 'missing' for any string key that is not present on the target, and returns the normal value otherwise.
Show answer
get(target, prop, receiver) { if (typeof prop === 'string' && !(prop in target)) return 'missing'; return Reflect.get(target, prop, receiver); }. The typeof check lets symbol reads such as Symbol.iterator pass through unchanged.