Log All Class Method Calls
class ConfusingClass {
constructor() {
logMethodCalls(this)
this.confuseMe = 1
this.someFn(300)
}
someFn(startVal = 1) {
this.confuseMe = startVal
this.testFn(() => this.otherFn(123))
}
testFn(fn) {
this.confuseMe += 1
fn(this.confuseMe)
}
otherFn(value = 111) {
this.confuseMe += 2
this.testFn(() => this.confuseMe += value)
this.confuseMe = this.add(this.confuseMe, 999)
console.log(this.confuseMe)
}
add(a, b) {
return a + b
}
}
const confusing = new ConfusingClass()
function logMethodCalls(target) {
const keys = Object.getOwnPropertyNames(target.constructor.prototype)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const propOrMethod = target[key]
if (typeof propOrMethod === 'function') {
target[key] = function(...args) {
console.log(key, '(', args.join(', '), ') - was run')
return propOrMethod.apply(target, args);
}
}
}
}
This one is good for dealing with confusing classes with lots of method calls. It logs any time a method is called, what its name is and what arguments were passed to it. Sometimes this really beats stepping through breakpoints, at least in my experience…