const target = { m: function() { console.log(this === proxy); } }; const handler = {}; const proxy = new Proxy(target,handler); target.m() // false proxy.m() // true
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 访
const target = new Date(); const handler = {}; const proxy = new Proxy(target,handler); proxy.getDate(); // TypeError: this is not a Date object.
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