What is Proxy and Reflect in JavaScript?
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.
No comments yet! You be the first to comment.
