ES6 Proxies in Depth by Ponyfoo

In notebook:
Article Notes
Created at:
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'
// <- '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).
create your proxy:
var {proxy, revoke} = Proxy.revocable(target, handler)
(using destructuring)
then revoke all access to it:
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
// <- 28