Created
June 12, 2019 19:31
-
-
Save mjstahl/b906a2a0504b2913232f957f9eb1b797 to your computer and use it in GitHub Desktop.
Proxy the context of a constructor function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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