Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

var F = function(){};

At first sight, the answer is no, but apparently the 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 {}

(Chrome)

Is this name somehow accessible? I need it mainly for error logging, so the solution doesn't have to be cross-browser.

Edit for clarification:

I'm getting an objects from external code that I need to know their types, therefore obvious answers like using another declaration ways are not what I'm searching.

like image 563
Ofir A. Avatar asked Mar 08 '16 15:03

Ofir A.


1 Answers

In the use-case that you're trying, it's possible that there can be more than one variable holding the same anonymous function.

ie, it can go on like:

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

So, now we have more than one name to look for. And the first thing I thought of is to loop through all the objects under window and print their name which is having the same method as the value.

So, you'd think of something like:

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

But, it doesn't work that way since, now item is another variable, and look like there is no built-in property that gives the variable name. May be, have a look at Variable name as a string in Javascript , not that it helps here, though...

So, finally, since you mentioned you're trying to do error logging, thought of using stack-traces. Don't know if it will apply in your situation, may be still a bit enlightening :)

And this is how it goes: (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, taking that 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 that will be:

myFunction

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

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

Have tried this only in Firefox, there's a chance the stack-trace might be different elsewhere.

Edit: Failed to notice your edit, this might need editing of declarations, which breaks your use-case. :(

like image 106
1ujn4s Avatar answered Oct 31 '22 06:10

1ujn4s