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

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

オープン
#2,904 コメント 0 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
HTML
スター
25.5k
フォーク
4k
PR マージ指標
30日以内にマージされた PR はありません

説明

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

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

https://javascript.info/proxy の Proxy に関する記事から始め、報告されている class と arrow function の挙動と併せてパスワードの例を確認してください。内部での this の使用と Proxy を介したアクセスに関する制限を説明するように記事を更新してください。この区別と回避策の文脈が正確に文書化されていれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript
領域
documentation
issue の種類
ドキュメント
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。