[英]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? 如果您有一个对象myObject
,可以使用什么函数来获取其名称? I've tried stuff like myObject.name
... 我已经尝试过像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. 如果重要的话,我建议您在创建对象时设置myObject.name
,然后再访问它,或者在函数中添加一个接受必要信息的附加参数。
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. 在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'. 该示例的结果将是两个不同的弹出窗口,一个带有“ test1”,另一个带有“ 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. 但是请记住,这不是您应该依靠的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.