Computer >> Computer tutorials >  >> Programming >> Javascript

What is the use of proxy() object in JavaScript?


Proxy()

One of the new features introduced by ECMAScript 6 is proxy() object. The Proxy() object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

Proxy() object includes 3 key terms

1) handler - It is a placeholder object which contains the traps.

2) traps - Traps provide property access.

3) target - it is an object, which the proxy virtualizes.

Syntax

var p = new Proxy(target, handler);

In the following example, there is an object called 'p' and it has some properties. When we try to execute the properties which are not defined in the object then undefined will be executed as shown in the output.

Example

<html>
<body>
<script>
   var p = {
      Name: 'Ram kumar',
      Age: 27
   };
   document.write(person.Name);
   document.write("</br>");
   document.write(person.Age);
   document.write("</br>");
   document.write(person.designation);
</script>
</body>
</html>

Output

Ram kumar
27
undefined


When proxy() is used we can eliminate the undefined output. Proxy() tries to trap the unknown property using "get" keyword. The handler, which is defined inside a proxy(), will pass the target and the requested key name in to the "get" trap.

In the following example initially the object 'p' has no designation and role. But later when proxy() came in to picture, the object and its properties were trapped using 'get' and unassigned properties were displayed as shown in the output.    

Example

<html>
<body>
<script>
   var p = {
      Name: 'Ram kumar',
      Age: 27
   };
   var handler = {
      get: function(target, prop) {
         return prop in target ? target[prop] : 'Content developer';
      }
   };
   var prox = new Proxy(p, handler);
   document.write(prox.Name);
   document.write("</br>");
   document.write(prox.Age);
   document.write("</br>");
   document.write(prox.designation);
   document.write("</br>");
   document.write(prox.role);
</script>
</body>
</html>

Output

Ram kumar
27
content developer
content developer