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() } }
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]) } 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 .: (