1

Consider the next example:

 function Test(){
    Log();
 }
 function Log(){
   console.log('Name of the called function');
 }

How do I get the name of the function, in this case Test(), Into my Log function without parameters of corse.

Consider that this works on this way:

function Hello(){
Log(); //should return Hello
}
function Test(){
Log(); //should return Test
}
function World(){
Log(); //should return World
}

function Log(){
return NAME_OF_FUNCTION;
}

Thanks

UPDATE:

I can use arguments.callee.name to get the name, but, this doesnt work on strict mode and If I delete de strict mode and I try to use it I get the name of clousure function and not the name of the parent method.. for example:

var Log = (function(){

function info(message){
console.log(arguments.callee) //This print function info(message){
}

return {
info:info
}
})();

function Test(){

Log.info("Some Message");

}

This is wrong, I need the name of Test function, not the info function.

cmarrero01
  • 691
  • 7
  • 21

2 Answers2

2

You could use this inside your function's body:

arguments.callee.caller.toString()

check this snippet:

function Test(){
    Log();
}

function Log(){
    alert(arguments.callee.caller.toString());
}

Test();

Update

If strict mode is used the above will not work.

Please read this, to see that Alex K. mentioned below in his comments. I didn't know it.

Community
  • 1
  • 1
Christos
  • 53,228
  • 8
  • 76
  • 108
2

This should do the job:

arguments.callee.caller.name

But careful: 'caller', 'callee', and 'arguments' properties cannot be used in strict mode they are deprecated in ES5 and removed in strict mode.

Exinferis
  • 689
  • 7
  • 17