【问题标题】:TypeScript class decorator for arrow function用于箭头功能的 TypeScript 类装饰器
【发布时间】: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


    【解决方案1】:

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

    所以当装饰器运行时,它不知道箭头函数。

    为此,您必须创建另一个装饰器,例如 @logMethod,并将其应用于方法声明。这可能会起作用,因为在这种情况下,装饰器将应用于属性,箭头函数本质上是一个属性。

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2020-03-28
      • 2018-09-30
      • 2018-06-02
      • 2017-05-13
      • 2017-11-15
      • 2022-08-15
      • 1970-01-01
      • 2010-11-22
      相关资源
      最近更新 更多