A JavaScript proxy object allows you to intercept and customize the behavior of another object without modifying the original object.
Proxy objects allow you to validate data, provide additional functionality, and control access to properties and functions.
Find out all about using proxy objects and how to create them in JavaScript.
Create a proxy object
In JavaScript you can create a proxy object using: proxy constructor. This constructor takes two arguments: the goal an object that wraps the proxy and handler An object with properties that define the behavior of the proxy when performing operations.
Takes these arguments and creates an object that can be used in place of the target object. This created object can redefine core operations such as getting, setting, and defining properties. You can also use these proxy objects to log property accesses and validate, format, or sanitize input.
for example:
const originalObject = {
foo: "bar"
}const handler = {
get: function(target, property) {
return target[property];
},
set: function(target, property, value) {
target[property] = value;
}
};
const proxy = new Proxy(originalObject, handler)
This code creates a target object. original objectwith a single property, Phewand the handler object, handlerThe handler object contains two properties. obtain and settingThese properties are known as traps.
A proxy object trap is a function that is called whenever a certain action is performed on a proxy object. Traps allow you to intercept and customize the behavior of proxy objects. When I access the property from the proxy object, obtain Invoking traps and modifying or manipulating properties from proxy objects setting trap.
Finally, the code creates a proxy object. proxy constructor.Passes original object and handler as the target object and handler respectively.
Using proxy objects
Proxy objects have several uses in JavaScript, some of which are listed below.
Adding Functionality to Objects
You can use proxy objects to wrap existing objects and add new functionality such as logging and error handling without modifying the original object.
To add new functionality, proxy Create a constructor and define one or more traps for the actions you want to intercept.
for example:
const userObject = {
firstName: "Kennedy",
lastName: "Martins",
age: 20,
};const handler = {
get: function (target, property) {
console.log(`Getting property "${property}"`);
return target[property];
},
set: function (target, property, value) {
console.log(`Setting property "${property}" to value "${value}"`);
target[property] = value;
},
};
const proxy = new Proxy(userObject, handler);
console.log(proxy.firstName);
console.log(proxy.lastName);
proxy.age = 23; // Setting property "age" to value "23"
This code block adds functionality via proxy traps. obtain and settingNow when I try to access or change the properties of the . User objectthe proxy object first logs the operation to the console before accessing or modifying the property.
Validate data before setting it in an object
You can use proxy objects to validate data to ensure that it meets certain conditions before populating the object with data.This will change the validation logic to setting to trap handler object.
for example:
const userObject = {
firstName: "Kennedy",
lastName: "Martins",
age: 20,
};const handler = {
get: function (target, property) {
console.log(`Getting property "${property}"`);
return target[property];
},
set: function (target, property, value) {
if (
property === "age" &&
typeof value == "number" &&
value > 0 &&
value < 120
) {
console.log(`Setting property "${property}" to value "${value}"`);
target[property] = value;
} else {
throw new Error("Invalid parameter. Please review and correct.");
}
},
};
const proxy = new Proxy(userObject, handler);
proxy.age = 21;
This code block sets the validation rule to setting trap. can be assigned any value. Year properties on User object Illustration. However, with the added validation rule, we can assign a new value to the age property only if it is a number greater than 0 and less than 120. Year Properties that do not meet the required criteria will trigger an error and print an error message.
Control access to object properties
A proxy object can be used to hide certain properties of an object.We do this by defining the limit logic in obtain Traps on properties that control access.
for example:
const userObject = {
firstName: "Kennedy",
lastName: "Martins",
age: 20,
phone: 1234567890,
email: "foo@bar.com",
};const handler = {
get: function (target, property) {
if (property === "phone" || property === "email") {
throw new Error("Access to info denied");
} else {
console.log(`Getting property "${property}"`);
return target[property];
}
},
set: function (target, property, value) {
console.log(`Setting property "${property}" to value "${value}"`);
target[property] = value;
},
};
const proxy = new Proxy(userObject, handler);
console.log(proxy.firstName);
console.log(proxy.email);
The code block above imposes certain restrictions on obtain trap.Initially you can access all available properties User objectAdded rules prevent access to sensitive information such as user emails and phone calls. Attempting to access any of these properties will result in an error.
Other proxy traps
of obtain and setting Traps are the most common and useful, but there are 11 other JavaScript proxy traps. they are:
- application: The· application Calling a function on the proxy object will execute the trap.
- To construct: The· To construct The trap is executed when you use the new operator to create an object from the proxy object.
- Delete property: The· Delete property is used to execute the trap. erase Remove a property from a proxy object using the operator.
- have – of have is used to execute the trap. of operator to check if a property exists on the proxy object.
- own key – of own key A trap is executed by calling any of the following: Object. getOwnPropertyNames again Object. getOwnPropertySymbols A function of the proxy object.
- getOwnPropertyDescriptor – of getOwnPropertyDescriptor A call to will execute the trap. Object. getOwnPropertyDescriptor A function of the proxy object.
- define Property – of define Property A call to will execute the trap. Object. defineProperty A function of the proxy object.
- Prevent extensions – of Prevent extensions A call to will execute the trap. Object. preventExtensions A function of the proxy object.
- expandable – of expandable A call to will execute the trap. Object. isExtensible A function of the proxy object.
- getPrototypeOf – of getPrototypeOf A call to will execute the trap. Object. getPrototypeOf A function of the proxy object.
- setPrototypeOf – of setPrototypeOf A call to will execute the trap. Object. setPrototypeOf A function of the proxy object.
like setting and obtain These traps can be used to add a new layer of functionality, validation, and control to an object without modifying the original object.
Disadvantages of proxy objects
Proxy objects are powerful tools for adding custom functionality and validation to your objects. But they also have some potential drawbacks. One such drawback is that it’s hard to debug because it’s hard to see what’s going on in the background.
Proxy objects can be difficult to use, especially if you are unfamiliar with them. Carefully consider these drawbacks before using proxy objects in your code.