我如何代理一个映射,然后访问代理映射的values?
下面是我正在尝试的代码:
const things = new Proxy(new Map(), {
set(t, k, v) {
console.log(t, k, v);
Reflect.set(t, k, v);
}
});
things['foo'] = 'bar'
// console log: Map(0) {} "foo" "bar"
console.log(things['foo']);
// console log: "bar"
things.values()
Uncaught TypeError: Method Map.prototype.values called on incompatible receiver [object Object]
at Proxy.values (native)发布于 2017-08-15 20:25:17
因此,如果Map方法的thisArg不是实际的Map对象,那么它就会抱怨。一种解决方案是向代理添加一个get,该代理检查正在获取的属性是否是一个函数,如果是,它将返回一个函数,该函数使用原始的非代理对象调用请求的函数。
const things = new Proxy(new Map(), {
set(t, k, v) {
console.log(t, k, v);
Reflect.set(t, k, v);
},
get(t, k) {
if (typeof t[k] === "function") {
return (...args) => Reflect.apply(t[k], t, args)
}
return t[k];
}
});其中一个潜在的缺点是返回的函数将有效地绑定到原始地图。在大多数情况下,可能不是一个问题,但它会使类似于things.values.call(someOtherMap)的调用变得毫无用处。如果这是个问题的话,也许有办法解决这个问题。
https://stackoverflow.com/questions/45700439
复制相似问题