1
class O {
  count = 0;
  add = () => {
    this.count++;
  };
}

const o = new O();
const po = new Proxy(o, {
  set(t, k, v, r) {
    console.log("set", k, v);
    return true;
  },
});

po.add();
console.assert(po.count === 1);

When calling add, the value is changed correctly, but why the set hook does not respond

januw a
  • 2,056
  • 5
  • 18
  • 39

1 Answers1

3

The set trap will only be entered into when something tries to assign to a property of the proxy. But your o class tries to assign to a property of this, where this is the instance, not the Proxy:

  add = () => {
    this.count++;
  };

Note that these class fields are equivalent to doing

class O {
  constructor() {
    this.count = 0;
    this.add = () => {
      this.count++;
    };
  }
}

so this always refers to the instance, rather than the proxy.

If you use a method or function instead, the calling context will be preserved, rather than always being the instance, and the .add being called from the Proxy will result in this being the Proxy in such cases:

class O {
  count = 0;
  add() {
    this.count++;
  };
}

const o = new O();
const po = new Proxy(o, {
  set(t, k, v, r) {
    console.log("set", k, v);
    return true;
  },
});

po.add();
console.log(po.count === 1);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320