InterviewHubPRO
Section Overview
Q199

Question 199 of 521

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

38%
JavaScript Internals (521 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

What is a proxy object

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
  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,

javascript
  //Example1:

  const person = {
    name: "Alex Morgan",
    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.

  1. Logging
  2. Authentication or Authorization
  3. Data binding and observables
  4. Function parameter validation

Note: This feature was introduced with ES6.