News for hackers. Stuff that matters.
Re:Proxy, a new JavaScript ES6 feature by foob on Friday May 18, 2018 @07:58AM (#17100684)
One possibility is adding syntactic sugar to objects. I posted elsewhere in this thread about how we used them in Remote Browser, but here's a simple example of adding support for negative indexing to an array. This basically creates a shorthand for array[-n] === array[array.length - n].

    class MyArray extends Array {
      constructor(...args) {
        super(...args);
        return new Proxy(this, {
          get: (target, name) => {
            if (name && name.match && name.match(/^-\d+$/)) {
              return Reflect.get(target, this.length + parseInt(name, 10));
            }
            return Reflect.get(target, name);
          },
          set: (target, name, value) => {
            if (name && name.match && name.match(/^-\d+$/)) {
              return Reflect.set(target, this.length + parseInt(name, 10), value);
            }
            return Reflect.set(target, name, value);
          },
        });
      }
    }
You could accomplish the same thing by creating explicit setters and getters, but proxies allow you to directly intercept and modify the behavior of property access, calling an object like a function, etc. This sort of flexibility allows you to create APIs that wouldn't be possible otherwise.

There are no comments on this comment yet.