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?

7 of 8 people (88%) answered Yes
Recently 3 of 4 people (75%) answered Yes

Entry

How do I find the name of a function?

Dec 13th, 2002 05:34
Klaus Bolwin, Bemi Faison, David Blackledge, jsWalter, Martin Honnen,


This answer deals with finding a function name, without knowing the name
of the function. This would be useful when trying to see what functions
have been loaded from an external library.
My research so far shows that, with NS 4-6 (Mac & PC), you can scan the 
top/self object using a for/in loop, to look for custom functions.
/-----snip
for (var i in top) { // for each top-level entity in the DOM...
   if (top[i]) { // first check if entity is accessible...
      if (top[i].toString().substring(1,9) == 'function ') { // if 
string value begins with the 'function '...
         document.write(i); // write custom function's name (or whatever
you like)
      }
   }
}
------snip/
In NS 6, this code will also capture some built-in functions, because they 
are now in the top/self object.
Shame, this doesn't work for IE. Sorry it's not cross-browser
compatible. But it's a start.
===============================
to get a reference to the current function without knowing its name, 
from within the function, use:
arguments.callee
then, based on the below code, you could do:
function (functionName(arg)
{
  alert(arguments.callee.getName())
}
Also, if your only reason for getting the current function's name is to 
get a reference to the current function, then you only need the 
arguments.callee, and none of the other stuff.
The reason for this property is so anonymous functions can be recursive, 
like:
var blah = new Function("arg","if(arg>0)arguments.callee(--arg);");
David.
http://David.Blackledge.com
----------------------------------
Nice work, but how can I get this to work within a Function?
function functionName (arg)
{
   alert(this.getName())
}
The above does not work.
wt - 5/13/02
=====================
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.