Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

amirhoseinsalimi
Copy link
Contributor

@amirhoseinsalimi amirhoseinsalimi commented Oct 16, 2023

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 proxied `Map` and doing such would raise an error of:
```
Uncaught TypeError: Method get Map.prototype.size called on incompatible receiver #<Map>
```

This PR provides a more general-purpose, yet simple example that works with both methods and properties.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant