2

I have a function called getItem. I want to read the name of this function using code from within it. Is this possible?

function getItem(){ 
   var functionName =   //how do I read the function name;
   alert(functionName)  //outputs 'getItem'
}
jarn
  • 263
  • 1
  • 2
  • 7
  • 1
    Who says a function even has to have a name? After all, javascript has great support for un-named functions. – Joel Coehoorn Apr 08 '11 at 18:51
  • @Joel Coehoorn, I know what you mean, but this function has a name because I made sure to give it one. Is there a way to get that name from within the function? – jarn Apr 08 '11 at 18:52
  • 1
    What problem are you trying to solve? Are you writing a testing framework and injecting this code into other functions? There might be a way to solve your problem without requiring the name of a function. – Dan Davies Brackett Apr 08 '11 at 18:56
  • possible duplicate of [Can I get the name of the currently running function in javascript?](http://stackoverflow.com/questions/1013239/can-i-get-the-name-of-the-currently-running-function-in-javascript) – Naftali Apr 08 '11 at 19:04
  • Possible duplicate of [Can I get the name of the currently running function in JavaScript?](https://stackoverflow.com/questions/1013239/can-i-get-the-name-of-the-currently-running-function-in-javascript) – Michael Freidgeim May 11 '19 at 22:58

3 Answers3

3

try this:

function getItem(){ 
   var functionName =   arguments.callee.name;
   alert(functionName)  //outputs 'getItem'
}

here is the fiddle: http://jsfiddle.net/maniator/xGzKA/

also see this previous stack Q for another solution

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

Though you should probably not use this, you can do this for IE, Firefox, Chrome, Safari, and Opera (I admit arguments.callee is convenient despite the valid reservations expressed about it, as would be arguments.callee.name if the Function.name property were standard):

function getFuncName (fn) {
    var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
    return name ? name[1] : '(Anonymous)';
}
Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
-1

Try this,

function getItem(){
    var functionName =  arguments.callee.name;
    alert(functionName);
}

http://jsfiddle.net/XPGxE/

Aravindan R
  • 3,084
  • 1
  • 28
  • 44
  • see http://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript – KooiInc Apr 08 '11 at 18:57
  • @Neal Didnt mean to copy. I posted the same answer almost the same time as you. Saw your answer only after posting. – Aravindan R Apr 08 '11 at 19:14