Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get function name in JavaScript

Tags:

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.

like image 208
kalan Avatar asked Jul 05 '10 10:07

kalan


People also ask

What is function name in JavaScript?

The function name property of the javascript object is used to return the name of the function. This name property of the function is only readable and cannot be altered. The name of the function which was given when the function was created is returned by Function.name.

Is get a function in JS?

The get keyword will bind an object property to a function. When this property is looked up now the getter function is called. The return value of the getter function then determines which property is returned.

What is the name of function?

A named function has 4 basic parts: the function keyword, the name you give it and use to refer to it, the parameter list, and the body of the function. Named functions can also be assigned to attributes on objects, and then you can call the function on the object: function sayHi() { console.

How do you call a function name my function?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.


1 Answers

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.

like image 174
Kamil Szot Avatar answered Sep 28 '22 21:09

Kamil Szot