javascript-tutorial / en.javascript.info

Modern JavaScript Tutorial
https://javascript.info
Other
23.33k stars 3.84k forks source link

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

Open amirhoseinsalimi opened 10 months ago

amirhoseinsalimi commented 10 months ago

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.