一些内置对象具有“内部插槽”,对这些对象的访问无法被代理
let map = new Map();
let proxy = new Proxy(map, {});
proxy.set('test', 1); // Error
解决:
let map = new Map();
let proxy = new Proxy(map, {
get(target, prop, receiver) {
let value = Reflect.get(...arguments);
return typeof value == 'function' ? value.bind(target) : value;
},
});
proxy.set('test', 1);
alert(proxy.get('test')); // 1
私有字段
私有字段是通过内部插槽实现的,在调用 getName() 时,this 的值是代理后的 user,它没有带有私有字段的插槽
class User {
#name = 'Guest';
getName() {
return this.#name;
}
}
let user = new User();
user = new Proxy(user, {});
alert(user.getName()); // Error
解决:
// 该解决方案也有缺点:它将原始对象暴露给该方法,可能使其进一步传递并破坏其他代理功能
class User {
#name = 'Guest';
getName() {
return this.#name;
}
}
let user = new User();
user = new Proxy(user, {
get(target, prop, receiver) {
let value = Reflect.get(...arguments);
return typeof value == 'function' ? value.bind(target) : value;
},
});
alert(user.getName()); // Guest
无法拦截严格相等性检查 ===
// 要包装的对象
let target = {};
// 代理配置
const handler = {
// 拦截写入
set(target, prop, val, receiver) {
return Reflect.set(target, prop, val, receiver);
},
// 拦截读取
get(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
},
};
// 代理对象
let proxy = new Proxy(target, handler);
let object = {
data: 'Valuable data',
};
let { proxy, revoke } = Proxy.revocable(object, {});
alert(proxy.data); // Valuable data
revoke();
alert(proxy.data); // Error