What is a proxy in javascript

Date: 30/03/2020

Introduction

Proxy in javascript is used to define custom behaviour for fundamental operations. We will have a proxy object where we will define our desired behaviour and wrap the object with proxy API.

Basic Example

const handler = {
  get: function(obj, prop) {
    return prop in obj ?
      obj[prop] :
      37;
  }
};

const p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;

console.log(p.a, p.b); 
//  1, undefined

console.log('c' in p, p.c); 
//  false, 37

The above example has an object that has a getter method. It acts as a getter method with setter only if the property doesn’t exist.

Syntax

const p = new Proxy(target, handler)

It has method revocable. The Proxy.revocable() method is used to create a revocable Proxy object.

We can also use methods such as set, apply in the handler and write our rules based on need and wrap it with Proxy API.
Check here for more info here https://javascript.info/proxy

Conclusion

Thanks for using pheonixsolutions. Share it with your friends to keep it alive if you find it useful.

Leave a Reply