javascript-tutorial / javascript-tutorial/en.javascript.info

Proxy and Reflect Article — Arrow Functions or `this` in Class constructor

Open
#2,904 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
HTML
Stars
25.5k
Forks
4k
PR merge metrics
No merged PRs in 30d

Description

**Source:** https://javascript.info/proxy
**Date Accessed:** 1 March 2022

A serious limitation in ES6 Proxy is the inability to proxy internal use of the `this` context inside a class. In the password example, if we use a class, then the differences in behaviour from using an arrow function vs a method is clear:

```ts

class User {

name = "John";
_password = "***";

checkPassword(value: string) {
return value === this._password;
}

checkPassword2 = (value: string) => {
return value === this._password;
}
};

const user = new Proxy(new User(), {

get(target: any, prop: string) {

if (prop.startsWith('_')) {
throw new Error("Access denied");
}
let value = target[prop];

// Commenting out the workaround
return value; // (typeof value === 'function') ? value.bind(target) : value; // (*)
},
});

console.log(user.checkPassword2('***')); // Arrow function works without the workaround because `this` is the internal context
console.log(user.checkPassword('***')); // Method fails with `Access denied` as expected

```

The point here is that if your class passes `this` somewhere in the constructor then that `this` cannot be proxied. This is a significant limitation of Proxy and should probably be mentioned in the article.

A good write up BTW.

Thanks

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the Proxy article at https://javascript.info/proxy and review the password example alongside the reported class and arrow-function behavior. Update the article to explain the limitation involving internal this use and Proxy access; done means the distinction and workaround context are accurately documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.