Open In App

What is the use of Proxy Object in JavaScript ?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Proxy in JavaScript is like a super helper for objects. It lets you control how an object behaves when you try to do things with it, like getting or setting properties. This is handy because you can customize an object’s behavior, making it do special things or preventing certain actions.

For example, you can use a Proxy to make sure that when you change a person’s age, it has to be a number. It’s like having a personal assistant for your objects that follows specific rules you set.

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.

Javascript




// 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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads