const emperor={name:'komei'};
const representative=new Proxy(emperor,{
get:(target,key)=>{return key in target?target[key]:"Don't bother the emperor!"},
set:(target,key,value)=>{
target[key]=value;}});
使用代理记录日志
function makeLoggable(target){return new Proxy(target,{
get:(target,property)=>{return target[property];},
set:(target,property,value)=>{
target[property]=value;}});}
function createNegativeArrayProxy(array){
if(!Array.isArray(array)){
throw new TypeError('Expexted an array');}return new Proxy(array,{
get:(target,index)=>{
index=+index;return target[index<0?target.length+index:index];},
set:(target,index,val)=>{
index=+index;return target[index<0?target.length+index:index]=val;}});}
const ninjas=["Yoshi","Kuma","Hattori"];
const proXiedNinjas=createNegativeArrayProxy(ninjas);
代理的性能限制
functionmeasure(items){conststartTime=newDate().getTime();for(leti=0;i<30000;i++){items[0]==="Yoshi";items[1]==="kuma";items[2]==="Hattori";console.log(i);}returnnewDate().getTime()-startTime;}constninjas=["Yoshi","Kuma","Hattori"];constproxiedNinjas=createNegativeArrayProxy(ninjas);console.log("proxies are around",Math.round(measure(proxiedNinjas)/measure(ninjas)),'times slower');