Forum Moderators: open

Message Too Old, No Replies

Dynamically alert the current function name

         

Fotiman

3:25 pm on Nov 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Is there a way to dynamically get the name of a function? Here's what I want to do:

function abc()
{
foo("Hello");
}
function xyz()
{
foo("Bye");
}
function foo(msg)
{
// Print "function: msg"
}
abc();
xyz();

Desired output:
foo(): Hello
xyz(): Bye

I don't know if this is possible. Ideally, I would like not to have to pass another variable to foo containing the function name... I just want it to dynamically "know" who called it. This is probably impossible, but thought I'd ask.
Thanks.

Fotiman

3:42 pm on Nov 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I think what I want is whatever arguments.caller was replaced with (caller was depreciated).

ajkimoto

5:01 pm on Nov 16, 2005 (gmt 0)

10+ Year Member



Fotiman,

I suppose you could define a global variable and populate it with the name of the function:

var lastFunc=''

function abc()
{
lastFunc='abc';
foo("Hello");
}

At least that way you won't have to pass the function name as a parameter.

Of course, 'deprecated' just means that they discourage you from using it, but it will still work. Also, there is no current replacement as far as I know.

ajkimoto

Fotiman

5:08 pm on Nov 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Well, I have resorted to something like this:

function abc()
{
foo("Hello",arguments.callee);
}
function xyz()
{
foo("Bye",arguments.callee);
}
function foo(msg)
{
if( arguments.length > 1 )
{
// Parse the function name and append it
}
// Print "function: msg"
}

I had hoped to avoid having to pass an argument, but there seems to be no good way around it. At least this way I can just use arguments.callee and I don't have to worry about the function names changing.