Table of Contents
Have you ever come across a situation where you need to intercept the operations of an object and control its behavior? If yes, then JavaScript Proxy Object can come in handy. In this article, we will take a deep dive into what is JavaScript Proxy Object, how it works, and its applications.
What is JavaScript Proxy Object?
JavaScript Proxy Object is an object that wraps another object and allows us to intercept and control its behavior. It acts as a middleman between the calling code and the object being called. It allows us to modify the default behavior of an object by intercepting its operations such as property access, property assignment, function invocation, etc.
How does JavaScript Proxy Object work?
The JavaScript Proxy Object works by defining a handler object, which contains a set of traps. These traps are functions that get called when a specific operation is performed on the proxy object. The handler object can intercept operations such as get, set, has, apply, construct, deleteProperty, and many more.
Creating a JavaScript Proxy Object
To create a JavaScript Proxy Object, we need to pass two arguments to the Proxy constructor. The first argument is the target object, which is the object that we want to wrap, and the second argument is the handler object, which contains the traps that intercept the operations on the target object.
Let’s see an example of creating a JavaScript Proxy Object:
const targetObj = {
name: 'John Doe',
age: 30,
city: 'New York'
};
const handler = {
get(target, property) {
console.log(`Getting ${property} value`);
return target[property];
},
set(target, property, value) {
console.log(`Setting ${property} value to ${value}`);
target[property] = value;
}
};
const proxyObj = new Proxy(targetObj, handler);
console.log(proxyObj.name);
// Output: Getting name value
// John Doe
proxyObj.age = 35;
// Output: Setting age value to 35
console.log(proxyObj.age);
// Output: Getting age value
// 35In the above example, we have created a target object with three properties: name, age, and city. We have also defined a handler object with get and set traps that intercept the get and set operations on the target object. Finally, we have created a JavaScript Proxy Object by passing the target object and handler object to the Proxy constructor.
Proxy Traps
Proxy traps are methods that define the behavior of a JavaScript Proxy object when a certain operation is performed on it. There are several traps available that can be used to customize the behavior of the Proxy object for various operations. Here are some commonly used Proxy traps:
The get() trap
This trap intercepts property access on the Proxy object. It takes three arguments: the target object, the property key, and the Proxy object. The trap returns the value of the property.
const user = {
firstName: 'John',
lastName: 'Doe'
}
const handler = {
get(target, property) {
return property === 'fullName' ?
`${target.firstName} ${target.lastName}` :
target[property];
}
};
const proxyUser = new Proxy(user, handler);
console.log(proxyUser.fullName);The set() trap
This trap intercepts property assignment on the Proxy object. It takes four arguments: the target object, the property key, the value to be assigned, and the Proxy object. The trap returns a Boolean indicating whether the assignment was successful.
const user = {
firstName: 'John',
lastName: 'Doe',
age: 20
}
const handler = {
set(target, property, value) {
if (property === 'age') {
if (typeof value !== 'number') {
throw new Error('Age must be a number.');
}
if (value < 18) {
throw new Error('The user must be 18 or older.')
}
}
target[property] = value;
}
};
const proxyUser = new Proxy(user, handler);The apply() trap
This trap intercepts function calls on the Proxy object. It takes three arguments: the target function, the this value, and an array of arguments passed to the function. The trap returns the result of the function call.
The construct() Trap
This trap intercepts object instantiation with the new keyword on the Proxy object. It takes three arguments: the target object, an array of arguments passed to the constructor, and the Proxy object. The trap returns the constructed object.
The getOwnPropertyDescriptor() Trap
This trap intercepts property descriptor access on the Proxy object. It takes two arguments: the target object and the property key. The trap returns the property descriptor of the property.
Applications of JavaScript Proxy Object
JavaScript Proxy Object has many applications. Here are some of the common use cases:
Validation
We can use the JavaScript Proxy Object to validate the properties of an object before setting their values. We can define a set trap in the handler object that checks the validity of the value before setting it to the property. If the value is not valid, we can throw an error.
Caching
We can use the JavaScript Proxy Object to cache the results of expensive operations. We can define a get trap in the handler object that checks whether the property value exists in the cache. If it does, we can return the cached value, otherwise, we can perform the expensive operation and store the result in the cache.
Logging
We can use the JavaScript Proxy Object to log the operations performed on an object. We can define traps in the handler object that log the operations such as get, set, apply, etc.
Conclusion
JavaScript Proxy Object is a powerful feature that allows us to intercept and control the behavior of an object. It is a great tool for implementing validation, caching, logging, and many other functionalities. With its help, we can achieve a greater degree of control and flexibility in our code.
Frequently Asked Questions?
What are some other common traps that can be defined in a JavaScript Proxy Object?
Some other common traps that can be defined in a JavaScript Proxy Object include the has trap, which intercepts property existence checks, the deleteProperty trap, which intercepts property deletion, and the apply trap, which intercepts function calls.
Can a JavaScript Proxy Object be used with arrays?
Yes, a JavaScript Proxy Object can be used with arrays just like any other object. We can define traps in the handler object that intercept operations such as array element access and modification.
Is the use of JavaScript Proxy Object recommended in production code?
The use of JavaScript Proxy Object is recommended in certain cases, such as implementing validation, caching, and logging functionalities. However, it should be used judiciously, as it can add complexity to the code and affect performance.
Is there any browser compatibility issue with JavaScript Proxy Object?
JavaScript Proxy Object is supported in most modern browsers, including Chrome, Firefox, Safari, and Edge. However, it is not supported in Internet Explorer and some older browsers.
Can a JavaScript Proxy Object be used to intercept operations on built-in objects such as Math and Array?
No, a JavaScript Proxy Object cannot be used to intercept operations on built-in objects such as Math and Array. This is because built-in objects are implemented in native code and do not have underlying JavaScript objects that can be wrapped with a proxy.

