【发布时间】:2020-04-25 13:24:44
【问题描述】:
我正在尝试跟踪 Typescript 类中的方法调用。类似于:https://github.com/aiteq/trace
代码正确地打印出greet1 方法的方法跟踪,但不是greet2 箭头函数。我相信它被视为一类财产。
关于如何打印出greet2 函数的跟踪的任何指针?
输出:
> ts-node test.ts
getOwnPropertyNames - methodName: constructor
getOwnPropertyNames - methodName: greet1
Call Greeter.greet1, args: ["test1"]
test1
test2
代码:
function logClass(target: any) {
if (target.prototype) {
Object.getOwnPropertyNames(target.prototype).forEach((methodName: string) => {
const original = target.prototype[methodName]
console.log(`getOwnPropertyNames - methodName: ${methodName}`)
if (typeof original !== 'function' || methodName === 'constructor') {
return
}
target.prototype[methodName] = function (...args: any[]) {
const ret = original.apply(this, args)
console.log(`Call ${target.name}.${methodName}, args: ${JSON.stringify(args)}`)
return ret
}
})
}
return target
}
@logClass
class Greeter {
public greet1(s: string) {
return s
}
public greet2 = (s: string) => {
return s
}
}
const greeter = new Greeter()
console.log(greeter.greet1('test1'))
console.log(greeter.greet2('test2'))
【问题讨论】:
标签: typescript typescript-typings javascript-decorators