Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Get function name inside of itself

Yes, I realize there are countless threads out there about this issue, for starters:

Get function name from function itself [duplicate]

Get function name from inside itself

Arguments.callee is deprecated - what should be used instead?

But the problem with the answers given is arguments.callee is deprecated. All of the answers say to just give your function a name. However, from what I can tell, that does not fix my problem. Say I have the following function:

function blah() {
  // arguments.callee.name is deprecated
  console.log('The function name is: ' + arguments.callee.name + '.');
}

But because that's deprecated, I shouldn't be using it, so what should I be using instead? Is there any way I can access the function name when inside the function itself, or am I just out of probability here?

If it makes things easier, I am using the framework Ext JS, but I haven't found a way of knowing the function's name. If not, is there a jQuery approach? I'm desperate here.

like image 687
incutonez Avatar asked Nov 02 '22 12:11

incutonez


1 Answers

You can provoke an exception and examine the stack trace.

The following proof of context works in the Chrome browser:

function test () {
  try { [].undef () } catch (e) {
     console.log (e.stack.split ('\n')[1].split (/\s+/)[2]);
  }
}

For a more robust implementation consult http://www.eriwen.com/javascript/js-stack-trace/ which provides a full stack trace in any browser.

A more modern and comprehensive stack trace analyzer is http://stacktracejs.com

like image 104
HBP Avatar answered Nov 09 '22 11:11

HBP