JavaScript · Question 78
How do Proxy and Reflect work together for JavaScript metaprogramming?
Direct answer
A Proxy intercepts specified internal object operations through traps, while Reflect provides function-style operations that closely correspond to those traps and is often the safest way to forward default behavior.
A proxy wraps a target and a handler. A get trap can observe or customize property reads, a set trap can intercept writes, and traps such as ownKeys, has, or construct intercept other language operations. This allows validation, virtualization, access tracking, reactive systems, and similar patterns.
Inside a trap, Reflect.get(target, key, receiver) is usually better forwarding code than simply evaluating target[key]. The Reflect operation mirrors the underlying semantics and preserves important arguments such as the receiver used by accessors.
- Proxy behavior is operation-based: intercepting
getdoes not automatically intercept every way a value can be discovered. - Proxies can add substantial conceptual complexity and may interfere with identity assumptions or debugging.
- Use
Reflectfor forwarding rather than manually reimplementing default semantics unless the behavior truly needs to differ.