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

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

未关闭
#2,904 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 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

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 https://javascript.info/proxy 上的 Proxy 文章开始,并结合报告中 class 和 arrow function 的行为检查密码示例。更新文章,解释涉及内部使用 this 和通过 Proxy 访问的限制;当这种区别以及变通方案的背景得到准确记录时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript
领域
documentation
Issue 类型
文档
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。