JavaScript(JS) Proxies

h‮:sptt‬//www.theitroad.com

JavaScript Proxies are a powerful feature in the language that allow you to intercept and customize the behavior of fundamental language operations on objects.

A Proxy is essentially a wrapper around an object that can intercept and handle operations performed on the object. When you create a Proxy, you define a set of functions called "traps" that will be called when certain operations are performed on the object.

Some of the most common traps include:

  • get: called when a property is accessed on the object
  • set: called when a property is set on the object
  • has: called when the in operator is used to check if a property exists on the object
  • deleteProperty: called when a property is deleted from the object
  • apply: called when the object is invoked as a function

Here is an example of creating a Proxy that intercepts property access on an object:

const obj = { name: "John", age: 30 };

const proxyObj = new Proxy(obj, {
  get: function(target, prop) {
    console.log(`Getting ${prop} from target`);
    return target[prop];
  }
});

console.log(proxyObj.name); // logs "Getting name from target" and "John"

In this example, the get trap intercepts property access on the proxyObj, logs a message to the console, and then returns the corresponding value from the original object.

Proxies can be used for a variety of purposes, such as data validation, access control, and debugging. They are a powerful tool for customizing the behavior of JavaScript objects.