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:

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();

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