en.javascript.info icon indicating copy to clipboard operation
en.javascript.info copied to clipboard

fix: fix the example of proxy limitations for `Map`

Open amirhoseinsalimi opened this issue 2 years ago • 0 comments

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.

amirhoseinsalimi avatar Oct 16 '23 20:10 amirhoseinsalimi