How to get the the variable name from within a function in this example:
// it should return A
var A = function(){ console.log(this.name); }
Is there something like this?
How to get the the variable name from within a function in this example:
// it should return A
var A = function(){ console.log(this.name); }
Is there something like this?
No, there is nothing like that in Javascript. That function is anonymous, so it has no name, and what you want is ambiguous because the function could just as easily have any number of variables referencing it like:
What is it you are actually trying to accomplish? I'm sure there is another way to achieve it.
I know this is an old thread, but still in search results. so just for reference:
a solution could simply be using the stacktrace.
use trim and split to get to the desired values.
It is possible in recent versions of Chrome and Firefox as follows. I only recommend this for debugging purposes (e.g. javascript tracing in non-production)
That function is anonymous; it has no name. You could, however, give it a name:
var A = function a() {};
Then its name is accessible via
Function.name
: