Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
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,
//Example1:
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);
//Example2:
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); // 10, null
console.log(“c” in p, p.c); // false, 100
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