Forward Proxy traps
A Proxy trap needs to log, validate, or transform an operation while retaining ordinary JavaScript behavior.
JavaScript · Module
Reflect is a namespace object containing static methods that invoke interceptable JavaScript object operations. It is primarily used to forward default behavior from Proxy traps.
Reflect is a namespace object whose static methods invoke JavaScript object internal methods, such as property access, assignment, construction, and function calls. It is especially useful inside Proxy traps when a trap should add behavior while preserving the operation's normal semantics.
ReflectEach static method returns the result specified by the corresponding operation; the exact return value depends on the method.
const target = { value: 1 };
const proxy = new Proxy(target, {
get(object, property, receiver) {
console.log(`Reading ${String(property)}`);
return Reflect.get(object, property, receiver);
},
set(object, property, value, receiver) {
return Reflect.set(object, property, value, receiver);
},
});
console.log(proxy.value);
proxy.value = 2;
console.log(proxy.value);The proxy logs reads while Reflect forwards the intercepted operations using JavaScript's default object behavior.
A Proxy trap needs to log, validate, or transform an operation while retaining ordinary JavaScript behavior.
Code needs to invoke property, construction, or function-call semantics explicitly rather than using syntax.
Meta-programming code needs operations that match Proxy handler trap semantics.
Reflect is a built-in namespace object containing static methods that correspond to interceptable object internal methods. It is not a constructor or callable function.
Follow-up: Why is it commonly used in Proxy traps? It provides the default forwarding operation, allowing the trap to add behavior without manually reproducing ordinary semantics.
A Proxy trap intercepts an operation, while the matching Reflect method performs the corresponding default internal operation. For example, a get trap can call Reflect.get with the target, property, and receiver.
Follow-up: Can Reflect bypass another proxy? No. The operation still goes through object internal methods, so a proxy target remains proxied.
Reflect methods use function-style forms of operations such as property lookup, assignment, construction, and invocation. This makes those operations explicit and useful for forwarding from traps.
Follow-up: What recursion risk exists? If a trap calls the corresponding Reflect method with the proxy as the target, the same trap can be triggered again indefinitely.
ProxyReflect.apply()Reflect.construct()Reflect.defineProperty()Reflect.deleteProperty()Reflect.get()Reflect.getOwnPropertyDescriptor()Reflect.getPrototypeOf()