ES6 Proxies in Depth by Ponyfoo

In notebook:
Article Notes
Created at:
2016-01-06
Updated:
2016-01-06
Tags:
JavaScript Fundamentals
ES6 Proxies in DepthUseful for creating, working with your models. Your objects are accessed through a proxy function that controls the operations.

var target = {}
var handler = {}
var proxy = new Proxy(target, handler)
proxy.a = 'b'
console.log(target.a)
// <- 'b'
console.log(proxy.c === undefined)
// <- true

The handler function (the proxy) can even have a ​get​ or ​set​ "trap". 

So now your models can be just "plain old JavaScript objects" (POJO) and the proxy will handle all setting, getting, transformations, without needing to rely on prototypal inheritance (or ES6 ​class​ classes).

The proxy object can function as a schema validator (reject unauthorised changes to your object).
Proxy.revocable
create your proxy:
var {proxy, revoke} = Proxy.revocable(target, handler)
(using destructuring)
then revoke all access to it:
​revoke()​ 
A more complete example:
  var validator = {
  set (target, key, value) {
    if (key === 'age') {
      if (typeof value !== 'number' || Number.isNaN(value)) {
        throw new TypeError('Age must be a number')
      }
      if (value <= 0) {
        throw new TypeError('Age must be a positive number')
      }
    }
    return true
  }
}
var person = { age: 27 }
var proxy = new Proxy(person, validator)
proxy.age = 'foo'
// <- TypeError: Age must be a number
proxy.age = NaN
// <- TypeError: Age must be a number
proxy.age = 0
// <- TypeError: Age must be a positive number
proxy.age = 28
console.log(person.age)
// <- 28