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

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

Offen
#2,904 0 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
HTML
Sterne
25.5k
Forks
4k
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

**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

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Rechercherichtung

Beginne mit dem Proxy-Artikel unter https://javascript.info/proxy und überprüfe das Passwortbeispiel zusammen mit dem gemeldeten Verhalten von Klassen und Arrow Functions. Aktualisiere den Artikel, um die Einschränkung im Zusammenhang mit der internen Verwendung von this und dem Zugriff über Proxy zu erklären; abgeschlossen ist die Aufgabe, wenn die Unterscheidung und der Kontext der Umgehungslösung korrekt dokumentiert sind.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
javascript
Bereich
documentation
Issue-Typ
Dokumentation
Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.