What is the use of Proxy Object in JavaScript ?
Last Updated :
31 Jan, 2024
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
const targetObject = {
name: 'Alice' ,
age: 25
};
const handler = {
get: function (target, prop) {
console.log(`Accessed property "${prop}" `);
return target[prop];
}
};
const proxiedObject =
new Proxy(targetObject, handler);
console.log(proxiedObject.name);
console.log(proxiedObject.age);
|
Output
Accessed property "name"
Alice
Accessed property "age"
25
Share your thoughts in the comments
Please Login to comment...