【问题标题】:Weird issue about JavaScript Proxy and getter functions关于 JavaScript 代理和 getter 函数的奇怪问题
【发布时间】:2021-10-28 04:41:58
【问题描述】:

两个测试用例都通过了。我根本不明白这种行为。似乎 JavaScript 代理无法捕获 getter 函数中的属性。

test('JS Proxy normal method', () => {
  class Store {
    hidden = false;
    visible() {
      return !this.hidden;
    }
  }
  const accessList: PropertyKey[] = [];
  const proxy = new Proxy<Store>(new Store(), {
    get: (target: any, propertyKey: PropertyKey) => {
      accessList.push(propertyKey);
      return Reflect.get(target, propertyKey);
    },
  });
  expect(proxy.visible()).toBe(true);
  expect(accessList).toEqual(['visible', 'hidden']);
});

test('JS Proxy getter method', () => {
  class Store {
    hidden = false;
    get visible() {
      return !this.hidden;
    }
  }
  const accessList: PropertyKey[] = [];
  const proxy = new Proxy<Store>(new Store(), {
    get: (target: any, propertyKey: PropertyKey) => {
      accessList.push(propertyKey);
      return Reflect.get(target, propertyKey);
    },
  });
  expect(proxy.visible).toBe(true);
  expect(accessList).toEqual(['visible']);
});

【问题讨论】:

  • 哪些期望失败了?如何失败?
  • 顺便说一句,您的 get 陷阱未将 receiver 参数转发到 Reflect.get
  • @Bergi 我希望两者在get 陷阱方面具有相同的行为。谢谢你的评论。您可以改为发布答案。
  • “顺便说一句,你的 get 陷阱没有将接收器参数转发给 Reflect.get”,这是根本原因!请发布答案,我会接受。非常感谢!

标签: javascript typescript getter es6-proxy


【解决方案1】:

您缺少属性访问权限的receiver。该属性可能定义在与访问它不同的对象上,您的Reflect.get 调用需要考虑到这一点。特别是,您作为argument of the get trap 获得的接收器是代理本身,这也是您要评估getter 的对象,因此它的this 值是指代理。但是,Reflect.get(target, propertyKey)target[propertyKey] 相同,其中getter 中的this 值设置为target,并且您的代理无法检测到.hidden 属性访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-28
    • 2021-08-27
    • 2011-07-17
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多