I have been exploring the Map
collection and came across the [[MapData]]
internal slot, which led me to utilize Reflect
for trapping purposes.
After some trial and error, I came up with the following code snippet:
const map = new Map();
const proxiedMap = new Proxy(map, {
get(target, property, receiver) {
const currentValue = Reflect.get(target, property, receiver);
return typeof currentValue === "function" ? currentValue.bind(target) : currentValue;
}
});
Although this code successfully works with methods like set
and get
, it encounters an error when handling size
.
proxiedMap.set("a", 1);
proxiedMap.get("a"); // 1
console.log(proxiedMap.size) // TypeError: Method get Map.prototype.size called on incompatible receiver #<Map>
To mitigate this issue, I removed the receiver
argument from Reflect. Surprisingly, this resolved the problem without fully understanding why.
const proxiedMap = new Proxy(map, {
get(target, property) {
const currentValue = Reflect.get(target, property)
return typeof currentValue === "function" ? currentValue.bind(target) : currentValue
}
})
Why does this inconsistency only seem to affect the behavior of the size
method?