this问题
虽然Proxy可以代理针对目标对象的访问,但他不是目标对象的透明代理,即不做任何拦截的情况下也无法保证与目标对象的行为一致。主要原因就是在Proxy代理的情况下,目标对象内部的this关键字会指向Proxy代理
const target = {
m : function(){
console.log(this === proxy);
}
};
const handler = {};
const proxy = new Proxy(target,handler);
target.m();
proxy.m();
由于this指向的变化导致Proxy无法代理目标对象
console.log('----------------------eg2------------------------');
const _name = new WeakMap();
class person{
constructor(name){
_name.set(this,name);
}
get name(){
return _name.get(this);
}
}
const jane = new person('jane');
console.log(jane.name);
const proxy1 = new Proxy({},jane);
console.log(proxy.name);
目标对象jane的name属性实际保存在外部Weakmap对象_name上面,通过this键区分。
由于通过proxy.name访问时,this指向proxy,导致无法取值,所以返回undefined
某些原生对象的内部属性只有通过正确this才能获取,所以Proxy也无法代理原生对象属性
Error
const target = new Date();
const handler = {};
const proxy = new Proxy(target,handler);
proxy.getDate();
const target2 = new Date();
const handler1 = {
get(target,prop){
if(prop === 'getDate'){
return target.getDate.bind(target);
}
return Reflect.get(target,prop);
}
};
const proxy2 = new Proxy(target2,handler1);
console.log(proxy2.getDate());
适合做Web服务的客户端,也可以来实现数据库的ORM层