Skip to content Skip to sidebar Skip to footer

How To Capture Proxy "set" Actions From A Class Constructor?

How do I trap actions where a property is set from inside a constructor? While here I am directly referencing Foo, in reality the Proxy implementation is inside a function with no

Solution 1:

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

classFoo {
  constructor() {
    setTimeout(() =>this.value = 'value', 1000)
  }
}

constTrap = Object.assign(function() {},  { 
  prototype: newProxy({}, {
    set(target, key, value) {
      target[key] = value;
      console.log("Set", target, key, value);
      returntrue;
    },
  }),
});

const $Foo = function () {
  returnReflect.construct(Foo, [], Trap);  
}

const foo = new $Foo();



setTimeout(() =>console.log(foo), 1100)

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

functionTrapMe(Super) {
  functionTrapped() {
    returnReflect.construct(Super, [], Trapped); 
  }
  
  Trapped.prototype = newProxy(Object.create(Super.prototype), {
    set(target, key, value) {
      target[key] = value;
      console.log("Set", target, key, value);
      returntrue;
    }
  });
  returnTrapped;
}

constFoo = TrapMe(classFoo {
  constructor() {
    console.log("constructed");
    setTimeout(() =>this.value = "value", 1000);
  }
});

newFoo();

Post a Comment for "How To Capture Proxy "set" Actions From A Class Constructor?"