To view this question, this question is similar to the following:
How do I get the type name of an object in JavaScript? Get runtime class name of an object in TypeScript
However, this is a little different.
I am looking to get the name of a method that belongs to a class and store it in a variable in TypeScript / JavaScript.
Take a look at the following setting:
class Foo { bar(){
The above value has a TypeScript value, and I would like to create a method in another class that will return the bar() method name to me, i.e. "bar"
eg:
class ClassHelper { getMethodName(method: any){ return method.name;
I would like to use ClassHelper as follows:
var foo = new Foo(); var barName = ClassHelper.getMethodName(foo.bar);
I looked through many posts, some suggest using the following:
var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec(obj.toString()); var result = results && results.length > 1 && results[1];
but this fails because my methods do not start with function
another suggestion was:
public getClassName() { var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec(this["constructor"].toString()); return (results && results.length > 1) ? results[1] : ""; }
This only returns the name of the class, but when reading messages it seems that using constructor may be unreliable.
Also, when I debugged the code using some of these methods, passing the method as follows: ClassHelper.getMethodName(foo.bar); will result in passing the parameter if the method accepts one, for example:
class Foo { bar(param: any){
I struggled with this for a while, if someone has information on how I can solve this, we will be very grateful.
My .toString() in the method passed returns this:
.toString() = "function (param) { // code }"
but not:
.toString() = "function bar(param) { // code }"
and according to MDN it is not intended:
That is, toString decompiles this function, and the returned string includes the function keyword, argument list, curly braces and the source of the function body.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString#Description