【ES6】Proxy

Proxy agent

Proxy used to modify the default behavior of some operations, equivalent to make changes in the language level, it is a kind of "meta-programming" (meta programming), that is the programming language for programming.

Proxy can be understood as, to set up a layer of "blocking" before the target object outside access to the object, this layer must first pass interception, thus providing a mechanism to filter and rewrite access to the outside world.

var obj = new Proxy({}, {
  get: function (target, propKey, receiver) {
    console.log(`getting ${propKey}!`);
    return Reflect.get(target, propKey, receiver);
  },
  set: function (target, propKey, value, receiver) {
    console.log(`setting ${propKey}!`);
    return Reflect.set(target, propKey, value, receiver);
  }
});

Redefined attribute read ( get) and set ( set) action. Proxy fact overload (overload) the dot operator, i.e. with their original definition overrides definition language.

var proxy = new Proxy(target, handler);

to intercept the target audience, handler parameter is an object, used to customize the behavior of interception. If you handlerdo not set any interception, it is equivalent to the direct access to the original object.

To make Proxywork, you must for the Proxyoperation instance, instead of the operation target object.

One trick is to Proxy object, setting the object.proxyproperty, which can be objectinvoked on the object.

var object = { proxy: new Proxy(target, handler) };

Proxy instance can be used as a prototype to another object.

var proxy = new Proxy({}, {
  get: function(target, propKey) {
    return 35;
  }
});

let obj = Object.create(proxy);
obj.time // 35

Details Reference: http://es6.ruanyifeng.com/#docs/proxy

 

Guess you like

Origin www.cnblogs.com/Mijiujs/p/12286581.html