在 Javascript 中获取变量的“名称”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3565031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:32:00  来源:igfitidea点击:

Get the 'name' of a variable in Javascript

javascriptvariables

提问by shdev

Possible Duplicate:
Determine original name of variable after its passed to a function.

可能的重复:
在传递给函数后确定变量的原始名称。

I would like to know if its possible to get the actual name of a variable.

我想知道是否有可能获得变量的实际名称。

For example:

例如:

var foo = 'bar';
function getName(myvar) {  
  //some code
  return "foo"  
};  

So for getName(foo) will return "foo"

所以对于 getName(foo) 将返回“foo”

Is that possible ?

那可能吗 ?

Thanks.

谢谢。

采纳答案by Mark Byers

I don't think it is possible. When you call a function you pass an object, not a variable. The function doesn't care where the object came from.

我不认为这是可能的。当你调用一个函数时,你传递的是一个对象,而不是一个变量。该函数不关心对象来自哪里。

You can go the other way though if you call your function as follows:

如果您按如下方式调用您的函数,您可以走另一条路:

getName('foo') 

Or pass both the value and the name:

或者同时传递值和名称:

getName(foo, 'foo')