关于 JavaScript 代理和 getter 函数的奇怪问题

Weird issue about JavaScript Proxy and getter functions

两个测试用例都blow都通过了。我根本不理解这种行为。似乎 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']);
});

你错过了 of the property access. The property might be defined on a different object than it is accessed on, and your Reflect.get call needs to take that into account. In particular, the receiver you get as a argument of the get trap 是代理本身,这也是你要评估 getter 的对象,所以它的 this 值是指代理.但是,Reflect.get(target, propertyKey)target[propertyKey] 相同,其中 getter 中的 this 值设置为 target.hidden 属性 您的代理无法检测到访问。