js 动态添加日志

const calculator = {
  count: 0,
  next() {
    return ++this.count
  },
  double(a) {
    return a * 2
  },
  add(a, b) {
    return a + b
  }

}
calculator.add(2, 3)
// function logging(fn){
//   fn.call()
// }
function logging(obj) {
  for (const key in obj) {
    const atr = obj[key]
    if (typeof atr === 'function') {
      obj[key] = function (...args) {
        console.log(atr.name)
        const ret = atr.apply(this, args)
        console.log(ret)
      }
    }
  }
}
logging(calculator)
calculator.double(3)

 

posted @ 2024-07-18 18:21  howhy  阅读(5)  评论(0编辑  收藏  举报