ES6 Proxies

A few days ago I was part of a BogotaJS event where each of the presenters had to talk about a new ES6 feature. The topic I chose was ES6 Proxies. I read about them in the past but didn’t pay too much attention. Turns out they are cool.

What are they for?

Proxies allow the developer to intercept typical operations with JS objects like setting a property, getting its value, enumerating it’s own properties and others.

The interesting part is that the default behavior can be overriden, so for example if the user tries to access a non existent property, a default one can be returned (instead of undefined)

var handler = {
  get(target, key){
    return 'you are trying to access:'+key
  }
}
var obj = {
  nombre: 'John',
  edad: 60
}

var proxy = new Proxy(obj, handler)
console.log('Name:'+ proxy.nombre) 
// Outputs: Name: you are trying to access:name

In the code above we rendered our object useless by always returning the string ‘you are trying to access:PROPERTY’ instead of the object value

Some interesting things that can be done with proxies:

Another not very practical example (but with potential applications). This proxy makes it possible to chain non existant properties and prints them to the console.

var handler = {}
handler.get = function(target, key){
  console.log(key)
  return new Proxy(function(){}, handler)
}

var obj = {}

var p = new Proxy(obj, handler)
p.hola.amigos.cómo.están();

This would print the string “hola amigos como están”. The trick is to return the same handler whenever a property value is requested. It doesn’t matter if the property exists.

Besides obvious uses like instrumentation or validation there may be creative uses of proxies out there worth exploring.