)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Log All Class Method Calls

  1. class ConfusingClass {
  2.   constructor() {
  3.     logMethodCalls(this)
  4.     this.confuseMe = 1
  5.     this.someFn(300)
  6.   }
  7.   someFn(startVal = 1) {
  8.     this.confuseMe = startVal
  9.     this.testFn(() => this.otherFn(123))
  10.   }
  11.   testFn(fn) {
  12.     this.confuseMe += 1
  13.     fn(this.confuseMe)
  14.   }
  15.   otherFn(value = 111) {
  16.     this.confuseMe += 2
  17.     this.testFn(() => this.confuseMe += value)
  18.  
  19.     this.confuseMe = this.add(this.confuseMe, 999)
  20.     console.log(this.confuseMe)
  21.   }
  22.   add(a, b) {
  23.     return a + b
  24.   }
  25. }
  26. const confusing = new ConfusingClass()
  27.  
  28. function logMethodCalls(target) { 
  29.   const keys = Object.getOwnPropertyNames(target.constructor.prototype)
  30.   for (let i = 0; i < keys.length; i++) {
  31.     const key = keys[i]
  32.     const propOrMethod = target[key]
  33.     if (typeof propOrMethod === 'function') {
  34.       target[key] = function(...args) {
  35.         console.log(key, '(', args.join(', '), ') - was run')
  36.         return propOrMethod.apply(target, args);
  37.       }
  38.     }
  39.   }
  40. }

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…

snippet.zone ~ 2021-24 /// {s/z}