zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[ES6] Proxy & Reflect

ES6amp Proxy reflect
2023-09-14 09:00:50 时间

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