Proxy & Reflect
Master JavaScript metaprogramming. Intercept and redefine fundamental object operations like reading, writing, and deleting properties.
The Interceptor
In JavaScript, interacting with objects is usually direct. If you write user.age = 25, the property is instantly updated.
A **Proxy** acts as a wrapper around a target object. It intercepts fundamental operations (reading, writing, deleting) and allows you to run custom code *before* the operation completes. Think of it as a security checkpoint.
Validation and Reactivity
Why intercept operations?
1. **Validation**: You can prevent someone from setting an invalid age (e.g., user.age = -5).
2. **Reactivity**: Frameworks like Vue 3 use Proxies to detect exactly when a property changes so they can automatically trigger UI re-renders.
3. **Logging**: You can log every time a specific property is read or written to.
Traps and Reflect
To create a Proxy, you provide a target object and a handler object containing 'traps' (interceptor functions).
javascript
const handler = {
set(target, prop, value) {
if (prop === 'age' && value < 0) throw new Error('Invalid age');
return Reflect.set(target, prop, value);
}
};
const proxy = new Proxy({}, handler);
**Reflect** is a built-in object that pairs perfectly with Proxy. After you run your custom logic, you use Reflect.set to actually apply the operation to the target object securely.
The Security Checkpoint
Study the architecture diagram below. It maps out the exact flow of data when a write operation (user.age = -5) hits the Proxy's set trap and is subsequently rejected by the validation logic.
The Security Checkpoint
set(obj, prop, value) {
if (prop === 'age' && value < 0) {
throw new Error('Invalid');
}
return Reflect.set(obj, prop, value);
}
});
Uncaught Error: Invalid
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A **Proxy** wraps an object and intercepts fundamental operations like reading or writing properties.
- The **handler** object contains 'traps' (e.g.,
get,set) that define the interception logic. - The **Reflect** API provides standard methods (e.g.,
Reflect.set()) to execute the default behavior safely. - Proxies are powerful for data validation, logging, and building reactive UI frameworks.
- Proxies carry a performance overhead compared to direct object access.
Done with this concept?
Mark it complete to track your progress. No login needed.