代理可以理解为拦截层,外界想要访问目标对象的时候,需要通过这个拦截层。
起到控制和授权的作用
举个🌰:
例如在家想访问公司的内网
例如明星的经纪人,无法直接联系到明星,只能通过经纪人间接联系到明星。
Proxy(target,handleFunctionObject)
处理函数对象,
有getter和setter,分别拦截读取操作和写入操作
有has,deleteProperty,拦截in操作和delete操作
明星经纪人实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| let famousStar = { name: "fanbingbing", age: "34", phone: "88888888", _time: "2019" } let starAgent = new Proxy(famousStar,{ get:function(target,key){ if(key==="phone"){ return "agent:1383838" }; if(key==="price"){ return 1000000 }; return target[key]; }, set:function(target,key,value){ if(value < 1000000){ throw new Error("100万一口价,低了免谈!") }else{ target[key] = value; return true; } }, has:function(target,key){ console.log("请联系agent:1383838") if(key === "customPrice"){ return target[key]; }else{ return false; } }, deleteProperty: function(target,key){ console.log("听说你想删除属性?") if(key.indexOf("_")==0){ delete target[key]; return true; }else { return false; } } });
console.log(starAgent.phone); console.log(starAgent.price); console.log(starAgent.name); console.log(starAgent.age);
starAgent.customPrice = 1080000; console.log(starAgent.customPrice);
starAgent.customPrice = 666666; console.log(starAgent.customPrice);
console.log("====has======") console.log("customPri" in starAgent)
delete(starAgent[name]);
delete(starAgent["_time"]);
|
Proxy支持的所有操作,可在Reflect对象上看
所以Reflect中的操作都可以使用
例如:
let obj = {a:1,b:2}
console.log(Reflect.get(obj,‘a’));
console.log(Reflect.has(obj,‘a’));