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.