ES6中的Proxy用來為對象的基本操作捣鲸,設置用戶自定義行為瑟匆。
例如:屬性查找,賦值栽惶,枚舉愁溜,函數(shù)調(diào)用,等等外厂。
例如:代理對象的屬性讀取
var handler = {
get: function(target, name){
return name in target?
target[name] :
37;
}
};
var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
例如:代理函數(shù)的調(diào)用和構(gòu)造
var f=function(){
alert(1);
};
var p=new Proxy(f,{
apply:function(){
alert(2); //2
f(); //1
},
construct:function(){
alert(3); //3
f(); //1
}
});
p(); //2 1
new p; //3 1