What is and what is the "Proxy" constructor in JavaScript for?

I know the constructor Proxy has been added In Version 6 of JavaScript (ES6). My questions are:

  • what is it?
  • what is its main purpose and how to use it?
Author: Luiz Felipe, 2018-08-21

1 answers

The Proxy object is a means to achieve a certain type of metaprogramming in JavaScript. In the field of metaprogramming, there are three broad categories:

  • introspection;
  • own modification;
  • interception.

The object Proxy, which works with the interception of objects, "encapsulates" an object and allows the interception of basic operations related to it, such as operations [[Get]] (of reading a property), [[Set]] (from setting a property) and many others. I will not quote the full list here, since it is extensive. For this, refer to this reference.

An object can be "proxied"like this:

const proxyfiedObject = new Proxy(targetObject, handler);

Where targetObject is the original object and proxyfiedObject is the object that will have the basic operations intercepted. Note that the original object is not affected. A new object is created.

The object handler is used to define the intercepts to be perform. For each of the operations supported by Proxy, there is a key that can be used on the handler object, associated with a callback function.

The example below illustrates interceptions of operations [[Get]]:

// Objeto original:
const original = {
  name: 'Foo',
  age: 50
};

// Objeto utilizado para definir as interceptações:
const handler = {
  get: (target, propKey) => {
    console.log('Operação [[Get]] chamada.');
    return `Modificada: ${target[propKey]}`;
  }
};

const proxyfied = new Proxy(original, handler);

console.log(proxyfied.name); // Irá ativar `handler.get`.

In this case, the use of a getter that would probably be enough. Proxy s are usually useful when you want to reuse the same handler for multiple objects or interception operations that go beyond mere [[Get]] or [[Set]].

Notice that the object Reflect implements all interceptable operations by Proxy. Both were introduced in ECMAScript 2015.

 2
Author: Luiz Felipe, 2020-11-23 23:42:11