Last active
February 27, 2022 22:50
-
-
Save USSliberty/48eada4819e112bb578c1fe9d7ae1ee7 to your computer and use it in GitHub Desktop.
Class Method Proxy Javascript
This file contains 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
function traceMethodCalls(obj) { | |
const handler = { | |
get(target, propKey, receiver) { | |
const targetValue = Reflect.get(target, propKey, receiver); | |
if (typeof targetValue === 'function') { | |
return function (...args) { | |
console.log('CALL', propKey, args); | |
return targetValue.apply(this, args); // (A) | |
} | |
} else { | |
return targetValue; | |
} | |
} | |
}; | |
return new Proxy(obj, handler); | |
} | |
class Test { | |
constructor () { | |
this.test = 1 | |
/** | |
* @type Test | |
*/ | |
this.deferred = traceMethodCalls(this); | |
} | |
incrementTest() { | |
this.test ++; | |
console.log(`incremented to ${this.test}`) | |
} | |
} | |
const tp = new Test(); | |
console.log(tp.deferred.incrementTest()) | |
// console.log(tp.incrementTest()); | |
console.log(tp.test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment