The previous example had a bug where you couldn't call size property from the proxied Map and doing such would raise an error of:
Uncaught TypeError: Method get Map.prototype.size called on incompatible receiver #<Map>
How to reproduce the bug in the example
1- According to the previous example, we have this code snippet:
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;
}
});
console.log(proxy.size);
2- We get an error suggesting that Map.prototype.size called on incompatible receiver.
How to fix:
1- We shouldn't pass all arguments to the Reflect.get as it forwards the receiver parameter, and causes the error above.
2- We just need to pass target and prop parameters to the Reflect.get method.
3- Now we can remove the unused receiver parameter from the method signature.
4- This will lead us to the code snippet below, which works fine with both methods and properties of the Map object.
let map = new Map();
let proxy = new Proxy(map, {
get(target, prop) {
let value = Reflect.get(target, prop);
return typeof value == 'function' ? value.bind(target) : value;
}
});
console.log(proxy.size);
This PR provides a more general-purpose, yet simple example that works with both methods and properties.
The previous example had a bug where you couldn't call
size
property from the proxiedMap
and doing such would raise an error of:How to reproduce the bug in the example
1- According to the previous example, we have this code snippet:
2- We get an error suggesting that
Map.prototype.size
called on incompatible receiver.How to fix:
1- We shouldn't pass all
arguments
to theReflect.get
as it forwards thereceiver
parameter, and causes the error above. 2- We just need to passtarget
andprop
parameters to theReflect.get
method. 3- Now we can remove the unusedreceiver
parameter from the method signature. 4- This will lead us to the code snippet below, which works fine with both methods and properties of theMap
object.This PR provides a more general-purpose, yet simple example that works with both methods and properties.