2

Possible Duplicate:
Get variable name. javascript “reflection”

Is there a way to know the name of a variable?

Example:

var a = 1;
var b = 4;

function getName(param){
    //What should I return here?
}

What I want to do, is to have getName return "a" if I call getName(a)and return "b" if I call getName(b)

Is this possible?

Community
  • 1
  • 1
ilyes kooli
  • 11,959
  • 14
  • 50
  • 79

3 Answers3

4

No, that's not possible in a clean way and I highly doubt there is a useful use-case for this.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • It's possible... somehow... http://stackoverflow.com/q/9795773/601179 – gdoron Jun 13 '12 at 13:14
  • 1
    I think I must be dense, but I can't see how the answer you're citing works. To me, it just seems like it gives you the formal parameter name ('x' in the linked example, 'param' in the OPs example). – Justin Blank Jun 13 '12 at 13:44
  • Yeah, that answer returns the name of the constructor function. – ThiefMaster Jun 13 '12 at 13:52
1

You could alter the prototype of the object to add a function to do this, as described in this StackOverflow answer:

Object.prototype.getName = function() { 
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};
Community
  • 1
  • 1
jeffjenx
  • 17,041
  • 6
  • 57
  • 99
  • Extending `Object.prototype` is a **bad thing**. It breaks all kind of stuff since scripts usually assume that iterating over an object defined e.g. via an object literal does not yield any functions unless they were defined in that literal. – ThiefMaster Jun 13 '12 at 13:19
  • @ThiefMaster, you are correct and I wouldn't recommend or use this, either. I am simply providing an answer to the question "Is there a way..." – jeffjenx Jun 13 '12 at 13:21
  • Doesn't seem to work: `var blah = 'moo'; (function(lol){print(lol.getName());})(blah);` => `String`. I think the OP wants the **variable name**, not the constructor name. Even though he did accept the answer... – ThiefMaster Jun 13 '12 at 13:31
-1

It isn't possible to get variable name. But you can get name of variable, who got exactly this value (if you got some vairables with equal values, you get first defined). And this function works only for global variables.

var a = 1;
var b = 4;

function test(value) {
  for (var x in window)
    if (window[x] === value)
      return x;
}

alert(test(b));
neworld
  • 7,757
  • 3
  • 39
  • 61