Thoughts from the office by Ed Ball
Wednesday, April 06, 2005

Have you ever wanted to determine programmatically the name of the function represented by a function object? There’s no direct way to get it, but there is an indirect way. The toString method of a function object returns the function declaration, from the function keyword at the start all the way to the last closing brace. Even “native” functions support the toString method in this fashion, though the implementation is omitted. This means that a simple regular expression can be used to determine the name of any function.

function GetFunctionName(fn)
{
  var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/);
  return m ? m[1] : "";
}

The regular expression simply finds the identifier after the function keyword. If it isn’t there (as can be the case with anonymous functions) GetFunctionName returns the empty string.

4/6/2005 4:22:20 PM (Pacific Daylight Time, UTC-07:00) | Comments [0] | Code | JavaScript#
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Search
Archive
Links
Categories
Administration
Blogroll