Updated April 15, 2023
Introduction to JavaScript proxy()
Today, we will discuss on JavaScript Proxy. It is one of the new features introduced in ES6 standards. JavaScript proxy() is an object in JavaScript that will wrap an object or a function to define the custom behavior of fundamental operations. Proxy() will help to create a proxy for another object which can be used to redefine fundamental operations to that object. Operations like read/ write, enumeration, property lookup, function calls, etc.are some of the fundamental operations which can be redefined. We shall face some new terms as we get deeper into the topic, let yourself push forward as this concept JavaScript proxy() is way much simpler and useful. Proxy on wrapping an object or a function is monitored by ‘target’, a new keyword we shall discuss here. Proxy being similar to metaprogramming in other languages as it is independent of wrapped object or function. Before we move into the coding part, there are some terminologies in Syntax which we need to understand,
Syntax:
let proxy = new Proxy(target, handler);
target and handler are the 2 parameters passed to the proxy().
- Targets: Object or a function which is to be proxied, the object can be a function, class or another proxy.
- Handler: An object which contains methods to control the behavior of proxy on performing some operation
Traps: Even though this parameter is not present in the proxy() syntax, we shall see its use later. These are the functions used to work on Targets.
We will be using Proxy Class from ES6 standard, hence arguments ‘target’ being the wrap object, ‘handler’ will be the function used on ‘target’ and to do some action on ‘target’, we use ‘trap’. If there is a ‘trap’ on the handler, the handler will run and proxy get a chance to handle it else these operations will be performed on ‘target’
How Does JavaScript proxy() Work?
- Proxy Object being a wrapper for target object where properties can be modified, the 3 main terms ‘target’, ‘handler’, and ‘traps’ will be helpful in this journey.
- Proxy traps the operations made to its target object and redirects all operations to handler objects.
- Then a proxy is created using new Proxy() with two parameters ‘target object’ and ‘handler object’
- A proxy is an exotic object, it does not have its own properties. If with empty ‘handler object, operations are forwarded to ‘target’
- We shall see a few examples to get a fair idea on how proxy() is implemented in real coding.
Examples to Implement JavaScript proxy()
Below are the examples of JavaScript proxy():
Example #1
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript proxy()</title>
</head>
<body>
<h2>Here, we will be displaying employeeNames</h2>
<script>
const target = {
employeeName1: "Karthick",
employer: "CPG"
};
const handler = {};
const proxy = new Proxy(target, handler);
document.write("Name of the Employee: " + proxy.employeeName1 + "<br/>");
document.write("Working in: " + proxy.employer);
</script>
</body>
</html>
Output:
Explanation: In this example above, we define two properties employeeName1 and employer and a handler with no properties. As there are no properties defined on the handler, proxy will behave like an original target and hence the output.
Example #2
Code:
<!DOCTYPEhtml>
<html>
<head>
<title>JavaScript proxy()</title>
</head>
<body>
<h2>Access data using Proxy and target</h2>
<script>
let target = {};
let proxy = new Proxy(target, {});
proxy.number = 100;
document.write("Using target: " + target.number + "<br/>");
document.write("using proxy: " + proxy.number + "<br/>");
for(let i in proxy) document.write("Looping: " + i + "<br/>");
</script>
</body>
</html>
Output:
Explanation: Here, all operations done on proxy are forwarded to target as there are no traps used here. Hence, proxy.number= sets value on target and proxy.number also returns a value from the target. On iterating proxy, target returns as ‘number’. With no traps here, the proxy is a transparent wrapper on target.get proxy.number.
Example #3
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript proxy()</title>
</head>
<body>
<h2>Here, we will be displaying student details with handler function</h2>
<script>
const student = {
stuName: 'Renuka',
stuSchool: 'SMHS',
stuAge: 12
};
const handler = {
get(target, property) {
document.write("<br/>" + `details as mentioned ${property}` + "<br/>");
return target[property];
}
};
const proxyStudent = new Proxy(student, handler);
document.write("Name of the student: " + proxyStudent.stuName);
document.write(" is studying in: " + proxyStudent.stuSchool);
document.write(" of age: " + proxyStudent.stuAge);
</script>
</body>
</html>
Output:
Explanation: Here, the student object has stuName, stuAge, and stuSchool as properties. Proxy is created and passed to the proxy constructor. A handler object with get functionality is created to perform an action on the proxy objects.
Let’s start adding traps,
get() trap: It is fired when the property of the target object is accessed using the proxy object. In our previous examples, the properties of the object are directly accessed by targets.
Here we would set a trap to compute properties of the target object. These properties are properties whose values are calculated based on the properties of existing values.
Likewise, we have set() trap, to control behavior when the target object’s properties are set.
- apply() trap: To trap a function call.
- construct() trap: To trap usage of the new operator.
- isExtensible() trap: To trap call to Object.isExtensible.
- delete() trap: To trap when deleting property and the list goes on. You people can explore on these traps further.
Example #4
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript proxy()</title>
</head>
<body>
<h2>Proxy with trap</h2>
<script>
const policy = {
policyName: 'Karthick',
policyGiver: 'SBI',
policyID: 123456,
}
const handler = {
get(target, property) {
return property === 'policydetails' ?
`${target.policyName} ${target.policyGiver} ${target.policyID}` :
target[property];
}
};
const proxyUser = new Proxy(policy, handler);
document.write(proxyUser.policydetails);
</script>
</body>
</html>
Output:
Advantages of JavaScript proxy()
Below are the advantages of JavaScript proxy():
- These agents ‘target’, ‘handler’,’trap’ will be helpful when the user wants to have control over data.
- User can able to spy on objects and ensure correct behavior of objects or functions.
- Useful in REST API calls, validation of data and monitoring Asynchronous functions.
- Also used in type checking and revocable references.
- Used in implementing DOM Document Object Model in JavaScript.
Conclusion
With this, we come to a conclusion of our topic’ JavaScript proxy(), As proxy() provides an interface to control the behavior of any target object using handler and trap, users can balance among simplicity and utility of an object. We have seen how JavaScript proxy() works with few examples illustrated using traps and without traps. You people can still explore the different traps mentioned here. We have seen a few advantages of using JavaScript proxy() with which you will get to know the use of a proxy() in your daily programming.
Recommended Article
This is a guide to JavaScript proxy(). Here we discuss the Introduction of JavaScript proxy() and the Code Implementation along with the Advantages. You can also go through our other suggested articles to learn more –