this
关键字会指向 Proxy 代理。const target = {
m: function () {
console.log(this === proxy);
}
};
const handler = {};
const proxy = new Proxy(target, handler);
target.m() // false
proxy.m() // true
上面代码中,一旦proxy代理target.m,后者内部的this就是指向proxy,而不是target。
this
指向的变化,导致 Proxy 无法代理目标对象。 const _name = new WeakMap();
class Person {
constructor(name) {
_name.set(this, name);
}
get name() {
return _name.get(this);
}
}
const jane = new Person(‘Jane‘);
jane.name // ‘Jane‘
const proxy = new Proxy(jane, {});
proxy.name // undefined 目标对象jane
的name
属性,实际保存在外部WeakMap
对象_name
上面,通过this
键区分。由于通过proxy.name
访问时,this
指向proxy
,导致无法取到值,所以返回undefined
const target = new Date(); const handler = {}; const proxy = new Proxy(target, handler); proxy.getDate(); // TypeError: this is not a Date object.getDate
方法只能在Date
对象实例上面拿到,如果this
不是Date
对象实例就会报错。this
绑定原始对象,就可以解决这个问题。
const target = new Date(‘2015-01-01‘); const handler = { get(target, prop) { if (prop === ‘getDate‘) { return target.getDate.bind(target); } return Reflect.get(target, prop); } }; const proxy = new Proxy(target, handler); proxy.getDate() // 1
原文:https://www.cnblogs.com/blogZhao/p/12564346.html