9.1.8 代理的问题与不足
1. 代理中的 this
const wm = new WeakMap();
class User {
constructor(userId) {
wm.set(this, userId);
}
set id(userId) {
wm.set(this, userId);
}
get id() {
return wm.get(this);
}
}
const user = new User(123);
console.log(user.id); // 123
console.log(userInstanceProxy.id); // undefined
这是因为 User 实例一开始使用目标对象作为 WeakMap 的键,代理对象却尝试从自身取得这个实
例。要解决这个问题,就需要重新配置代理,把代理 User 实例改为代理 User 类本身。之后再创建代
理的实例就会以代理实例作为 WeakMap 的键了:
const UserClassProxy = new Proxy(User, {});
const proxyUser = new UserClassProxy(456);
console.log(proxyUser.id);
刚开始自己不懂什么意思,userInstanceProxy和user中的this是它们自己本身,但是userInstanceProxy不等于user。map中存的键值是user不是userInstanceProxy,所以拿不到值。其实和WeakMap没有任何关系,用map存值也会有这种问题。