1

If you have an object myObject, what function can you use to get its name? I've tried stuff like myObject.name...

3 Answers 3

7

You can't get the name of the variable that an object was stored in. In fact, multiple variables can refer to a single object (which one would be the "name"?), probably the very reason you asked.

If it is important, I would suggest setting myObject.name when you create the object and then access it later, or perhaps add an additional parameter to your function that accepts the necessary information.

1
  • +1 setting the name to use it later, this is arguably the best way to do what you want cleanly.
    – Christian
    Dec 30, 2010 at 22:28
2

You can't.

Even if you could, which of the multiple variables that could be pointing at the object would you want?

1

There was a similar question about this in PHP. The short answer is "you can't", but the longer one is "you can to a certain extent".

Here's an example:

test1={};
test2={};
test1b=test1;

function findName(ref){
   for(var i in window)
      if(window[i]===ref)
         alert('Found: '+i);
}

findName(test1);

The result of the example would be two different popups one with 'test1' and another one with 'test1b'.

Again, this is an example, no need for bashing about using global variables, etc...

Edit: Come to think of it, I'm pretty sure I needed something like this for debugging, and it seemed to work out nicely. But bear in mind it isn't something you should rely on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.