Sometimes you need more than getters and setters.
You want to **observe, validate, or modify behavior** whenever an object is used.
`Proxy` and `Reflect` make this possible in a clean, standardized way.
🔹 What Is `Proxy`?
A `Proxy` wraps an object and intercepts operations such as:
- Property access
- Assignment
- Deletion
- Function calls
```js
const proxy = new Proxy(target, handler);
The handler defines traps for these operations
🔹 Common Proxy Traps
get – Intercept Reads
const user = { name: "Vu" };
const proxy = new Proxy(user, {
get(target, prop) {
console.log("Reading:", prop);
return target[prop];
}
});
🔹Set – Intercept Writes
const proxy = new Proxy({}, {
set(target, prop, value) {
if (typeof value !== "string") {
throw new TypeError("Value must be a string");
}
target[prop] = value;
return true;
}
});
🔹 Why Reflect Exists
Reflect provides methods that:
• Match Proxy traps
• Return booleans instead of throwing
• Are safer than direct operations
Example:
Reflect.set(target, prop, value);
Reflect.get(target, prop);
🔹 Proxy + Reflect Together (Best Practice)
const proxy = new Proxy(user, {
get(target, prop) {
return Reflect.get(target, prop);
},
set(target, prop, value) {
return Reflect.set(target, prop, value);
}
});
This keeps behavior predictable and consistent.
🔹 Real-World Use Cases
• Validation layers
• Access control
• Debug logging
• Reactive systems
• Framework internals (Vue, MobX)
🔹 Common Mistakes
❌ Overusing Proxy for simple tasks
❌ Forgetting to return true in set
❌ Breaking expected object behavior
🔹 Best Practices
• Use Proxy sparingly
• Prefer Reflect inside traps
• Keep traps lightweight
• Avoid surprising behavior
🔹 Limitations
• Slight performance overhead
• Can make debugging harder
• Not ideal for hot paths
🎯 Final Thought
Proxy changes how objects behave,
Reflect keeps that behavior safe and consistent.
Used wisely, they unlock powerful patterns in JavaScript.