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