JS Proxy and Reflect
In this page:
Proxy Basics
A Proxy lets you intercept operations on an object. A handler defines what should happen. Common traps include get, set, has, and deleteProperty, each corresponding to a fundamental operation you can observe or override on the wrapped object.
Example: Proxy Basics
const handler = {
get(target, prop) {
console.log("Reading:", prop);
return target[prop];
},
};
const obj = new Proxy({ name: "Sam" }, handler);
console.log(obj.name);
Intercepting Property Changes
The set trap runs when a property is assigned through the Proxy. Without a set trap, changes to the proxy fall straight through to the underlying object; with one, you can log, validate, or reject the change before it happens.
Example: Intercepting Property Changes
const handler = {
set(target, prop, value) {
console.log("Setting", prop, "to", value);
target[prop] = value;
return true;
},
};
const obj = new Proxy({}, handler);
obj.age = 30;
Using Reflect
Reflect provides standard methods for object operations. It works well inside Proxy traps. Reflect's methods mirror the default behavior a trap would otherwise need to reimplement manually, so calling Reflect.get/set inside a trap lets you extend rather than replace default behavior.
Example: Using Reflect
const handler = {
get(target, prop) {
return Reflect.get(target, prop);
},
};
const obj = new Proxy({ name: "Sam" }, handler);
console.log(obj.name);
Validation with Proxy
A Proxy can validate values before storing them. Throwing or returning false from inside a set trap (paired with Reflect.set for the valid cases) lets you enforce constraints, like requiring a property stay within an allowed range.
Example: Validation with Proxy
const handler = {
set(target, prop, value) {
if (prop === "age" && value < 0) {
throw new RangeError("Age cannot be negative");
}
return Reflect.set(target, prop, value);
},
};
const user = new Proxy({}, handler);
user.age = 30;
console.log(user.age);
Practical Proxy Example
Proxy is useful for logging, validation, defaults, and controlled access to object properties. Because traps run for every relevant operation, Proxy is useful for building reactive systems, ORMs, and API wrappers that need to react to arbitrary property access transparently.
Example: Practical Proxy Example
const handler = {
get(target, prop) {
console.log(`Accessed ${prop}`);
return Reflect.get(target, prop);
},
};
const logged = new Proxy({ id: 1 }, handler);
console.log(logged.id);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: