In javascript, how to find out the name of a function from this function?

Possible duplicate:
How can I get a function name inside a JavaScript function?

The title should be clear.

Is it possible to define the name of this function from within the function?

Basically, I am adding some debugging code to many functions, and I would just like to add the following line inside each function:

if (global_debugOn) alert("Processing function " + function-name); 

How can I get the 'function-name'?

Yes, obviously, I could just enter the name of the function (I’m typing the entire alert bit), but this is a hassle, especially if there is a good easy way to get it dynamically. Also, since function names change during development, I would like to keep it up to date ...

I was hoping that perhaps the arguments attribute might contain this (for example, arguments[0] , as in C), but I could not get it to work. I'm not even sure if arguments .

Thanks!

Rory

+4
source share
3 answers

The closest thing is arguments.callee , which actually returns the function itself, not the name.

The only thing arguments.caller that returns a string, but this is only in Mozilla and is not even supported there ..

The final option is to call arguments.callee.toString() .. but this will return a function declaration, not just the name.

+2
source

you can say arguments.callee.toString (), and the name may be there. this will not happen if you declare the function anonymously, that is, var f = function () {} as opposed to the function f () {}

0
source
 function someFunc() { var ownName = arguments.callee.toString(); ownName = ownName.substr('function '.length); ownName = ownName.substr(0, ownName.indexOf('(')); alert(ownName); } someFunc(); 
0
source

Source: https://habr.com/ru/post/1310184/


All Articles