Sure! Let’s break down Proxy and Reflect in JavaScript clearly. They are closely related and introduced in ES6 to provide more control over objects.
1. Proxy
A Proxy is an object that wraps another object (called the target) and allows you to intercept and redefine fundamental operations on that object, like reading/writing properties, function calls, or even object construction.
Syntax:
let proxy = new Proxy(target, handler);
target→ The original object you want to wrap.handler→ An object with traps (methods) to intercept operations.
Example: Intercepting property access
let person = { name: "Himanshu", age: 25 };
let proxyPerson = new Proxy(person, {
get(target, prop) {
console.log(`Getting ${prop}`);
return target[prop];
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
target[prop] = value;
return true; // indicate success
}
});
console.log(proxyPerson.name); // Getting name → Himanshu
proxyPerson.age = 30; // Setting age to 30
Other common traps:
deleteProperty→ interceptdeleteoperationshas→ interceptinoperatorapply→ intercept function callsconstruct→ interceptnewoperator
2. Reflect
Reflect is a built-in object that provides methods for default object operations—similar to the operations you can intercept with Proxy. It’s not a constructor; it’s just a collection of static methods.
Think of it as a utility that mirrors the default behavior of objects.
Common methods:
Reflect.get(target, property, receiver)→ same astarget[property]Reflect.set(target, property, value, receiver)→ same astarget[property] = valueReflect.has(target, property)→ same asproperty in targetReflect.deleteProperty(target, property)→ same asdelete target[property]
Example: Using Reflect inside Proxy
let person = { name: "Himanshu", age: 25 };
let proxyPerson = new Proxy(person, {
get(target, prop) {
console.log(`Getting ${prop}`);
return Reflect.get(target, prop); // default behavior
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
return Reflect.set(target, prop, value); // default behavior
}
});
console.log(proxyPerson.age); // Getting age → 25
proxyPerson.age = 26; // Setting age to 26
Why use Reflect?
- It helps maintain default behavior while using Proxy.
- Makes Proxy handlers simpler and less error-prone.
- Some Proxy traps require returning
true/false; Reflect does that automatically.
Summary Table
| Feature | Purpose |
|---|---|
| Proxy | Intercept operations on objects (get, set, delete, etc.) |
| Reflect | Provides default object operations as methods, useful inside Proxy |
✅ Key idea:
- Proxy → lets you control how an object behaves.
- Reflect → lets you perform default operations safely.
