JavaScript 中如何获取对象的名称?
如果你有一个对象 myObject
,你可以使用什么函数来获取它的名称?我尝试过类似 myObject.name
...
If you have an object myObject
, what function can you use to get its name? I've tried stuff like myObject.name
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法获取存储对象的变量的名称。事实上,多个变量可以引用一个对象(哪个是“名称”?),这可能就是您问的原因。
如果它很重要,我建议在创建对象时设置
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?
PHP 中也有类似的问题。
简短的答案是“你不能”,但较长的答案是“你在某种程度上可以”。
下面是一个示例:
该示例的结果将是两个不同的弹出窗口,一个带有“test1”,另一个带有“test1b”。
再说一遍,这是一个示例,无需抨击使用全局变量等...
编辑:想想看,我很确定我需要一些东西像这样进行调试,看起来效果很好。但请记住,这不是您应该依赖的东西。
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:
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.