kalan kalan - 1 month ago 8
Javascript Question

Get function name in JavaScript

Does anyone know if there is a way to get JavaScript function name. For example I got a function like

function test1(){
alert(1);
}


I have it in my head section. Then I create an object obj1 and put my function there

obj1.func = test1;


When I call a method in obj1 object, do I have any way to get my function name (test1) inside of this method, except parsing the source (
this.func.toString()
) of the function.

Answer
function test() {  alert(arguments.callee.name); } 
b = test; 
b();

outputs "test" (in Chrome, Firefox and probably Safari). However, arguments.callee.name is only available from inside the function.

If you want to get name from outside you may parse it out of:

b.toString();

but I think name property of function object might be what you need:

alert(b.name);

this however does not seem work for IE and Opera so you are left with parsing it out manually in those browsers.

Comments