在 ES6 代理的构造函数中设置属性的陷阱

问题描述

我有代码

class Foo {
  a: number;
  b?: number;

  constructor() {
    this.a = 1;

    setTimeout(() => {
      this.b = 2;
    },1000);
  }

  update() {
    this.a = 10;
    this.b = 20;
  }
}

const instance = new Foo();

const proxy = new Proxy(instance,{
  set: function (target: Foo,prop: keyof Foo,value: any): boolean {
    console.log("update prop:",prop,value);

    target[prop] = value;
    return true;
  }
});

proxy.update();

结果:

update prop: a 10
update prop: b 20

我也想记录在类构造函数中所做的更改,所以结果应该是:

update prop: a 1  // set in constructor
update prop: a 10
update prop: b 20
update prop: b 2  // set in constructor setTimeout

我知道为什么这段代码不像我想要的那样工作,但我不知道如何编写这种代码。这可能吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)