The Proxy object is used to define custom behavior for fundamental operations such as property lookup, assignment, enumeration, function invocation, etc.
A proxy is created with two parameters: a target object which you want to proxy and a handler object which contains methods to intercept fundamental operations. The syntax would be as follows,
var p = new Proxy(target, handler);
Let's take a look at below examples of proxy object and how the get method which customize the lookup behavior,
const person = {
name: "Sudheer Jonna",
age: 35,
};
const handler = {
get(target, prop) {
if (prop === "name") {
return "Mr. " + target[prop];
}
return target[prop];
},
};
const proxy = new Proxy(person, handler);
var handler1 = {
get: function (obj, prop) {
return prop in obj ? obj[prop] : 100;
},
};
var p = new Proxy({}, handler1);
p.a = 10;
p.b = null;
console.log(p.a, p.b);
console.log("c" in p, p.c);
In the above code, it uses get handler which define the behavior of the proxy when an operation is performed on it. These proxies are mainly used for some of the below cross-cutting concerns.
- Logging
- Authentication or Authorization
- Data binding and observables
- Function parameter validation
Note: This feature was introduced with ES6.