How do I trap actions where a property is set from inside a constructor?
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();