DarkLightA
DarkLightA

Reputation: 15662

How do you get the name of an object in JavaScript?

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

Upvotes: 1

Views: 136

Answers (3)

Christian
Christian

Reputation: 28124

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.

Upvotes: 1

PleaseStand
PleaseStand

Reputation: 32082

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.

Upvotes: 7

Quentin
Quentin

Reputation: 943556

You can't.

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

Upvotes: 2

Related Questions