Proxy Object in javascript

Asked

Viewed 98 times

2

I came across a type of object called proxy in javascript which is its real utility?

And what would be the traps/traps?

1 answer

4


The Proxy comes to solve an old need, to be able to intercept and redirect code dependent on logic. A little abstract maybe, but (and although this is possible with elaborate methods) the Proxy allows listening to changes in an object and reacting without who requested a value being affected.

More concrete: using Proxy we can have a virtual object, without properties and through Proxy manage what is returned from each request (get) to that object.

Example:

const objetoVazio = {bar: ''};
let somaDeSetters = 0;
const objetoVirtual = new Proxy(objetoVazio, {
  get: function(objeto, chave) {
    if (!(chave in objeto)) {
      console.log('Tentou aceder a um valor que não existe!');
      return null;
    }

    return objeto[chave];
  },
  set: function(objeto, chave, valor) {
    if (!(chave in objeto)) {
      console.log('Tentou settar a um valor que não existe!');
      return null;
    } else {
      console.log(`A chave ${chave} já foi setada ${(somaDeSetters++)} vezes`);
      objeto[chave] = valor;
    }
  }
});
objetoVirtual.foo = 200;
objetoVirtual.bar = 'baz';
objetoVirtual.bar = 'buzz!';

var x = objetoVirtual.foo;
var y = objetoVirtual.bar;
console.log(x, y); // null, buz

In this example above we check before get and set whether the object has the requested key/property. I suggested a similar function in the Vuex library. Another possibility would be to validate Type, for example in Forms. If the set value is not of the same type (number, string, etc.) as the key allows then we can return an error or a warning and prevent over-write the value.

Proxy opens numerous possibilities to control objects, arrays, etc, allowing you to have full control over the initial object that is never exposed to those who wish to modify it.

  • 1

    Really interesting to think about using proxies as a form validation helper.

Browser other questions tagged

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