Skip to content

Instantly share code, notes, and snippets.

@USSliberty
Last active February 27, 2022 22:50
Show Gist options
  • Save USSliberty/48eada4819e112bb578c1fe9d7ae1ee7 to your computer and use it in GitHub Desktop.
Save USSliberty/48eada4819e112bb578c1fe9d7ae1ee7 to your computer and use it in GitHub Desktop.
Class Method Proxy Javascript
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