views:

75

answers:

3

Possible Duplicate:
How can I get the name of function inside a JavaScript function?

The title should make it clear.

Is it possible from within a function to determine the name of that function?

Basically, I'm adding some debugging code to a number of functions, and I'd like to be able to simply add the following line inside every function:

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

How can I get 'function-name'?

Yes, obviously I could simply type in the function name (after all I'm typing in the whole alert bit), but that's a hassle to do, especially if there is a nice simple way of retrieving it dynamically. Plus, as function names change during development, I'd like to keep it up-to-date...

I hoped that maybe the arguments attribute might hold this (e.g. arguments[0], like in C), but I couldn't get it to work. I'm not even sure if arguments works anyway.

Thanks!

Rory

+2  A: 

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

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

One last option is to call arguments.callee.toString() .. but that will return the function declaration, not just the name.

Matt
So just call `arguments.callee.toString()` and parse it to display whatever you need? For example, trim it so everything after and including the first bracket is removed.
Duracell
@Duracell the output of that `toString()` is implementation-dependent and may not even contain the function name. I've seen some return "`[object Function]`". It is not reliable.
Matt
Oh ok. Ouch. Looks like the best way the is to assign a name to the function as a member then.
Duracell
A: 

you can say arguments.callee.toString() and the name may be in there. it won't if you declare the function anonymously, i.e. var f = function () {} as opposed to function f(){}

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

someFunc();
Strelok
or in a line-String(arguments.callee).split('(')[0];
kennebec