What is and what is the "Proxy" Javascript constructor for?

Asked

Viewed 71 times

3

I know the builder Proxy was added in Javascript version 6 (ES6). My questions are:

  • What is?
  • What is its main purpose and how to use it?
  • 2

    Luiz, I found a text that talks a little about this here

1 answer

2


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

  • Introspection;
  • Own modification;
  • Interception.

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

An object can be "proxyfied" like this:

const proxyfiedObject = new Proxy(targetObject, handler);

In which targetObject is the original object and proxyfiedObject is the object that will have the basic operations intercepted. Note that the original object nay is affected. A new object is created.

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

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 would probably be enough. The Proxys are generally useful when you want to reuse the same handler for multiple objects or the interception of operations that go beyond mere [[Get]] or [[Set]].

Note that the object Reflect implements all interceptable operations for Proxy. Both were introduced in Ecmascript 2015.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.