I want to get the name of the current method from within an instance method of a class in Typescript.
(Pseudocode, doesn't work):
class Foo {
bar() {
console.log(something); //what should something be?
}
}
new Foo().bar();
I expect 'something' to return 'bar'. I realize that this
can give me the class, and I could somehow get the class and its attributes from it, but I do not know how to get 'this function' (i.e, the method bar, not the class Foo).
I have seen several other questions related to finding the class name, etc. but not one that addresses getting the current method name.
Besides the
arguments.callee.name
there is no straightforward way of getting this.I propose 2 other methods:
Use decorators to inject the method name:
The downside is that you have to annotate all the functions you want to get the name from. You could instead just annotate the class and in the decorator you would iterate over all prototype functions and apply the same idea.
My second option is not standardised and need more care to get consistent results across browsers. It relies on creating an Error object and getting it's stack trace.
Not sure if this would help, but:
for class name -
Foo.name
for method name -this.bar.name