2

The problem

I need to fetch the name of an anonymous function defined as an expression when it is called.


What I've tried so far

In the following example, I am able to console.log the name of the function like this:

function init() {
    console.log(init.name); // Outputs "init".
}

The console.log will output init respectively. When I define the function as an expression, console.log(init.name); will no longer output init, because technically I'm asking for the name of an anonymous function (as proven by console.log(init); in the second example).

var init = function() {
    console.log(init.name); // Outputs nothing.
};

The following example will initially solve the problem, as suggested by robertklep:

var init = function init() {
    console.log(init.name); // Outputs "init".
};

This way, I give the anonymous function a name and I can just fetch the name with init.name. Although, this is not the solution I'm looking for.


The question

Is it possible to obtain the name of an anonymous function defined as an expression when it is called at all? Am I forced to give the function a name too if I want to achieve this?

Audite Marlow
  • 1,034
  • 1
  • 7
  • 25
  • Possible duplicate of [Javascript get Function Name?](http://stackoverflow.com/questions/2648293/javascript-get-function-name) – ADreNaLiNe-DJ May 26 '16 at 11:58
  • It would have been, was it not for the anonymous function expression. Is there a way to get the name of the variable inside the anonymous function? – Audite Marlow May 26 '16 at 12:12

3 Answers3

4

You can't, because coded like that, it's an anonymous function (in other words: it doesn't have a name).

But you can give it a name if you like:

var init = function theFunctionName() {
  console.log(init.name); // outputs: theFunctionName
};
robertklep
  • 198,204
  • 35
  • 394
  • 381
1

Anonymous function without having any name will give black string if you try .name.

var init = function() {
  console.log(typeof init.name);// will give blank string 
};

But if you give name to function it will give you name.

Manwal
  • 23,450
  • 12
  • 63
  • 93
-2

You can try it like this :

console.log(init.toString());
Rambler
  • 4,994
  • 2
  • 20
  • 27