开发者

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

开发者 https://www.devze.com 2023-02-02 09:04 出处:网络
If you have an object myObject, wh开发者_开发技巧at function can you use to get its name? I\'ve tried stuff like myObject.name...You can\'t get the name of the variable that an object was stored in. I

If you have an object myObject, wh开发者_开发技巧at function can you use to get its name? I've tried stuff like myObject.name...


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.


You can't.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号