[ES6] Proxy & Reflect

Proxy and Reflect API works nicely together.

About how to use Proxy, check this post.

Let's see about Reflect API:

const obj = {name: "foo"};
console.log(Reflect.get(obj, "name")); // "foo"

 

For proxy and Reflect, their API is really similar:

const target = {name: "foo"};
const handler = {
    get: function(target, key){
      console.log("Accessd key", key);
      return Reflect.get(target, key); // using Reflect to get the value
    },
    set: function(target, key, value){
      console.log('Update key', key, "to", value);
      Reflect.set(target, key, value); // using Reflect to set the value
    }
  };

function logAccessToProperties(obj) {
  return new Proxy(obj, handler);
}

const l = logAccessToProperties(target);
console.log(l.name); //foo
l.age = 23
console.log(l.age ); //23

 

posted @ 2018-04-18 19:49  Zhentiw  阅读(152)  评论(0)    收藏  举报