javascript-tutorial / javascript-tutorial/en.javascript.info
Proxy and Reflect Article — Arrow Functions or `this` in Class constructor
- Lingua principale
- HTML
- Stelle
- 25.5k
- Fork
- 4k
- Metriche di merge delle PR
- Nessuna PR unita negli ultimi 30g
Descrizione
**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
Guida per i contributori
Nessuna guida per i contributori indicizzata per questo repository
Direzione di ricerca
Inizia dall’articolo su Proxy all’indirizzo https://javascript.info/proxy e rivedi l’esempio della password insieme al comportamento segnalato delle classi e delle arrow functions. Aggiorna l’articolo per spiegare la limitazione relativa all’uso interno di this e all’accesso tramite Proxy; il lavoro è completo quando la distinzione e il contesto della soluzione alternativa sono documentati accuratamente.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript
- Ambito
- documentation
- Tipo di issue
- Documentazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Stato di attività
- Ferma
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 45/100