Skip to content

Instantly share code, notes, and snippets.

@mjstahl
Created June 12, 2019 19:31
Show Gist options
  • Save mjstahl/b906a2a0504b2913232f957f9eb1b797 to your computer and use it in GitHub Desktop.
Save mjstahl/b906a2a0504b2913232f957f9eb1b797 to your computer and use it in GitHub Desktop.
Proxy the context of a constructor function
// Thanks @phillipskevin
function wrap(C) {
const instanceHandler = {
set(target, property, value, receiver) {
console.log(property, value);
return true;
}
}
const constructorHandler = {
construct(target, args) {
const instanceProxy = new Proxy(Object.create(C.prototype), instanceHandler);
C.apply(instanceProxy, args);
return instanceProxy;
}
}
return new Proxy(C, constructorHandler);
}
function Counter() {
setInterval(this.onTick.bind(this), 1000)
}
Counter.prototype.onTick = function() {
const now = new Date()
// want to call the set trap
this.hours = now.getHours()
// want to call the set trap
this.minutes = now.getMinutes()
// want to call the set trap
this.seconds = now.getSeconds()
};
Counter = wrap(Counter);
const instance = new Counter();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment