用于箭头函数的 TypeScript 类装饰器



我正在尝试跟踪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'))

如果您查看生成的代码,这是不可能的,您将看到箭头函数是在构造函数中创建的,它们不是原型的一部分。

因此,当装饰器运行时,它不知道箭头功能。

为此,您必须创建另一个像@logMethod这样的装饰器并将其应用于方法声明。在这种情况下,装饰器将应用于属性,箭头函数本质上是一个属性。

最新更新