4

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?

Adam Halasz
  • 57,421
  • 66
  • 149
  • 213

4 Answers4

11

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:

var A = function a() {};
A.name
> 'a'
Ross Allen
  • 43,772
  • 14
  • 97
  • 95
  • 1
    @Adam: Yes, and no. It's supported by all browsers, but there are some implementation bugs, for example: http://stackoverflow.com/questions/8548840/javascript-named-function-expressions-in-internet-explorer – Guffa Jan 06 '13 at 01:34
5

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

a solution could simply be using the stacktrace.

var stack = new Error().stack;

use trim and split to get to the desired values.

SomeOne_1
  • 808
  • 10
  • 10
  • no, although very nice idea, it won't work, you'll get something like:`...at :2:5`. I've tried some other OO ways like injecting a method to the object.constructor.prototype, then executing it from the object itself, or simple adding a method that will return the stack to the object itself, both ways executing the method seems to still output the stack running a nameless constructor.. :( –  Jan 10 '15 at 01:51
2

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:

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 is it you are actually trying to accomplish? I'm sure there is another way to achieve it.

Paul
  • 139,544
  • 27
  • 275
  • 264
2

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)

var myNameInChrome = /.*Object\.(.*)\s\(/.exec(new Error().stack)[0];
var myNameInFF = new Error().stack.split("@")[0];
Lightbeard
  • 4,011
  • 10
  • 49
  • 59