Get anonymous function name

How to get the variable name from a function in this example:

// it should return A var A = function(){ console.log(this.name); } 

Is there something like this?

+4
javascript function variables anonymous-function names
source share
4 answers

This function is anonymous; he has no name. You could, however, give him a name:

var A = function a() {};

Then its name is available through Function.name :

 var A = function a() {}; A.name > 'a' 
+9
source share

I know this is an old thread, but still in the search results. so for reference:

solution can just use stacktrace.

 var stack = new Error().stack; 

use trim and split to get the values ​​you need.

+3
source share

No, there is nothing like that in Javascript. This function is anonymous, therefore it does not have a name, and what you want is ambiguous, because the function can just as easily have any number of variables referring to it:

 var a, b, c, d; a = b = function(){ console.log(this.name); }; c = b; d = c; a = b = 5; // a and b no longer refer to the function, but c and d both do 

What are you really trying to achieve? I am sure there is another way to achieve this.

+2
source share

In recent versions of Chrome and Firefox, this is possible as follows. I recommend this for debugging purposes only (e.g. javascript trace in non-production)

 var myNameInChrome = /.*Object\.(.*)\s\(/.exec(new Error().stack)[0]; var myNameInFF = new Error().stack.split("@")[0]; 
+2
source share

All Articles