Is it possible to get the name of an anonymous JavaScript function?

Is it possible to get the name of an anonymous function declared as follows?

var F = function(){}; 

At first glance, the answer is negative, but, apparently, browsers know and hold the function name:

 var F = function(){}; var x = new F(); console.log(x.constructor); // function F() 

(Firefox)

 var F = function(){}; var x = new F(); console.log(x); // F {} 

(chromium)

Is this name somehow accessible? I need this mainly for reporting errors, so the solution should not be a cross browser.

Edit for clarification:

I get objects from external code that I need in order to know their types, so obvious answers like using other declaration methods are not what I'm looking for.

+7
javascript function logging
source share
1 answer

In the use case that you are trying, it is possible that there may be several variables containing the same anonymous function.

those. It may continue as:

 var F = function(){}; var x = new F(); var x2 = x; var x3 = x; var blah = x3; 

So now we have some names to search for. And the first thing I thought was to iterate over all the objects under the window and print their name, which has the same method as the value.

So, you would think of something like:

 for each (item in window){ if (myfunc == item){ console.log(/*Somehow print the actual name of the item */) } } 

But since then it does not work, now item is another variable, and it looks like there is no built-in property that gives the variable name. Maybe look at the variable name as a string in Javascript , not that it helps here, though ...

So, finally, since you mentioned that you were trying to register errors, you thought about using stack traces. I don’t know if it will be applied in your situation, maybe a little more enlightening :)

And so it is: (To be warned, this is a hack)

 var myFunction = function(){ var err = new Error(); console.log(err.stack) } myFunction(); 

will output something like:

 myFunction@debugger eval code:3:17 @debugger eval code:6:5 @debugger eval code:1:15 

And, going to the next level:

 var myFunction = function(){ var err = new Error(); console.log(err.stack.split("@")[0]) /* split the stack-trace string and get the first word before @ */ } myFunction(); 

Now the output for this will be:

 myFunction 

Which, indeed, is the name of the variable that holds the anonymous function.

Note. This answer is inspired by the question. How can I get a Javascript stack trace when throwing an exception?

I tried it only in Firefox, there is a chance that the stack trace may be different elsewhere.

Edit: Failed to notice your editing, this may require editing ads, which violates your use case .: (

+2
source share

All Articles