es6 proxy proxy learning

In-depth es6 has a detailed introduction to the agent. In-depth es6: http://www.infoq.com/cn/es6-in-depth/

The following is my actual test example.

Basic usage of proxy.

// proxy = new Proxy(target,hander)  

// The method called by the proxy is the method that calls the target object, or the method in the handle object that is overridden in 14.
//The 14 methods in the hander are the default 14 methods of Object

// If you rewrite set, get will redefine the behavior of ., which can prevent assignment and value operations, and you can easily monitor property changes, similar to set, get in Object.defineProperty(obj,key,{set,get})

 

(function(){

 

var target={c:12,d:33};
var proxy = new Proxy(target,{
get:function(target,key,receiver)
{
console.log("get...")
return Reflect.get(target,key,receiver);
},
set:function(target,key,value,receiver){
console.log("set...")
}
})

// proxy.account=1;
// console.log(proxy.account);

console.log(proxy.c);


})() ;

(function(){

//The agent can realize the automatic filling of attributes. The principle is to monitor the assignment operation and create one if it is found not.

function Tree() {
return new Proxy({}, handler);
}
var handler = {
get: function (target, key, receiver) {
if (!(key in target)) {
target[key] = Tree(); // 自动创建一个子树
}
return Reflect.get(target, key, receiver);
},

};

var tree = Tree ();
tree.aa.aa.aa.aa = 1;
}) ();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325851641&siteId=291194637