faqts : Computers : Programming : Languages : JavaScript : Language Core : Functions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 11 people (55%) answered Yes
Recently 4 of 8 people (50%) answered Yes

Entry

How do I find the name of a function?

Jul 8th, 2004 03:48
Thomas White, Martin Honnen,


There is no built in property for the name of a function but you can 
parse the result of
  functionObject.toString()
for it. The following adds a method
  getName
for function objects which returns the name of a function:

function Function_getName () {
  return this.toString().split(' ')[1].split('(')[0];
}
Function.prototype.getName = Function_getName;

Example use:

function functionName (arg) { }
alert(functionName.getName())

Note that the format of functionObject.toString() is implementation 
dependant. The above code is tested with NN4 and IE5 and works but 
might fail for other implementations of JavaScript.

--------------
I hope this will help.

function getFnName( s ) {
  var a = s.match( /function\s(\w*)\s*\(/ );
  return a ? a[1]:'unknown';
}

function whoami(){
  var s = whoami.caller.toString();
  return getFnName( s );
}

function AFunctionWhichNameWeDoNotKnow(){
  var myNameIs = whoami();
  ....

}

Thomas