What is the use of Proxy Object in JavaScript ?
In JavaScript, the Proxy object acts as a assistant for objects, allowing fine-grained control over their behavior when accessing or modifying properties. With Proxy, you can customize an object’s behavior, enforcing specific rules or implementing special actions.
For instance, you might employ a Proxy to ensure that when modifying a person’s age property, it must always be assigned a numerical value. This capability enables you to create objects with tailored behaviors, akin to having a dedicated assistant for managing your objects according to predefined rules.
Example: Here, we create an Proxy
object that wraps around the targetObject
. The handler
has a get
trap that logs a message when a property is accessed. When we access properties of the proxiedObject
, the get
trap is triggered, allowing us to customize the behavior accordingly.
// Creating a target object
const targetObject = {
name: 'Alice',
age: 25
};
// Creating a handler with a trap
// for the get operation
const handler = {
get: function (target, prop) {
console.log(`Accessed property "${prop}"`);
return target[prop];
}
};
// Creating a proxy object
const proxiedObject =
new Proxy(targetObject, handler);
// Interacting with the proxy
// Output: Accessed property "name", Alice
console.log(proxiedObject.name);
// Output: Accessed property "age", 25
console.log(proxiedObject.age);
Output
Accessed property "name" Alice Accessed property "age" 25