javascript-tutorial / javascript-tutorial/en.javascript.info
Proxy and Reflect Article — Arrow Functions or `this` in Class constructor
還沒有人認領這個 Issue。
- 主要語言
- 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
貢獻指南
這個儲存庫沒有索引到貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 https://javascript.info/proxy 上的 Proxy 文章開始,並結合回報中 class 和 arrow function 的行為檢視密碼範例。更新文章,說明涉及內部使用 this 和透過 Proxy 存取的限制;當這項區別以及替代方案的背景獲得準確記錄時,即視為完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- javascript
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 2/5
- 預估耗時
- 1-3 小時
- 活躍度
- 停滯
- 描述清晰度
- 描述清楚
- 新手友好度
- 45/100