How to capture Proxy “set” actions from a class constructor?

后端 未结 1 993
臣服心动
臣服心动 2021-01-28 02:37

How do I trap actions where a property is set from inside a constructor?

相关标签:
1条回答
  • 2021-01-28 03:14

    You could create a Proxy on the prototype of the class:

    class Foo {
      constructor() {
        setTimeout(() => this.value = 'value', 1000)
      }
    }
    
    const Trap = Object.assign(function() {},  { 
      prototype: new Proxy({}, {
        set(target, key, value) {
          target[key] = value;
          console.log("Set", target, key, value);
          return true;
        },
      }),
    });
    
    const $Foo = function () {
      return Reflect.construct(Foo, [], Trap);  
    }
    
    const foo = new $Foo();
    
    
    
    setTimeout(() => console.log(foo), 1100)

    As a function injecting the trap that could be written as:

    function TrapMe(Super) {
      function Trapped() {
        return Reflect.construct(Super, [], Trapped); 
      }
      
      Trapped.prototype = new Proxy(Object.create(Super.prototype), {
        set(target, key, value) {
          target[key] = value;
          console.log("Set", target, key, value);
          return true;
        }
      });
      return Trapped;
    }
    
    const Foo = TrapMe(class Foo {
      constructor() {
        console.log("constructed");
        setTimeout(() => this.value = "value", 1000);
      }
    });
    
    new Foo();

    0 讨论(0)
提交回复
热议问题