有没有办法在TypeScript类中获取方法/函数名称?
以下TypeScript代码旨在在运行时打印类名称和方法名称。使用this.constructor.name
可以很好地使用类名,但是如何获得方法名?
export class MyClass {
public myMethod() {
console.log('Class name: ' + this.constructor.name);
console.log('Method name: ' + XXX);
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
如果您想以更通用的方式(跨领域关注)来封装myMethod
调用和其他调用的日志记录,则可以使用decorator:
function log<A extends any[], R>(
target: Object,
methodName: string,
descriptor: TypedPropertyDescriptor<(...args: A) => R>) {
let method = descriptor.value!; // this is the wrapped function
descriptor.value = function (...args: A) {
// instead of methodName, method.name works as well to get its name
console.log("Calling", methodName, "with", args, "from", target.constructor.name)
return method.apply(target, args);
}
}
class MyClass {
@log
public myMethod() { }
@log
public myMethod2(s: string) { return 42 }
}
new MyClass().myMethod() // Calling myMethod with Array [] from MyClass
new MyClass().myMethod2("foo") // Calling myMethod2 with Array [ "foo" ] from MyClass
这里是sample。请注意,此功能尚不稳定,必须通过experimentalDecorators
编译器选项启用。