JS Coding Questions Logo
JS Coding Questions
#195💼 Interview💻 Code

What is a proxy object

Advertisement

728x90

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,

javascript
1var 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,

javascript
1//Example1:
2
3const person = {
4  name: "Sudheer Jonna",
5  age: 35,
6};
7
8const handler = {
9  get(target, prop) {
10  if (prop === "name") {
11  return "Mr. " + target[prop];
12  }
13  return target[prop];
14  },
15};
16
17const proxy = new Proxy(person, handler);
18
19//Example2:
20
21var handler1 = {
22  get: function (obj, prop) {
23  return prop in obj ? obj[prop] : 100;
24  },
25};
26
27var p = new Proxy({}, handler1);
28
29p.a = 10;
30
31p.b = null;
32
33console.log(p.a, p.b); // 10, null
34
35console.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.

1. Logging

2. Authentication or Authorization

3. Data binding and observables

4. Function parameter validation

Note: This feature was introduced with ES6.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 25

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
195of476