[英]How to get variables names inside a javascript function
我想在这个例子https://jsfiddle.net/8dw9e5k7/中得到“a,b”,而不是得到别的东西。 可能吗?
function test() {
a = 5;
b = 10;
try {
var variables = ""
for (var name in this)
variables += name + "\n";
alert(variables);
} catch(e) {
alert(e.message)
}
}
test();
在 function 中分配不存在的变量会使变量成为全局变量,这意味着附加到window
object。 这就是为什么您的代码有些工作并显示变量以及许多其他内容的原因,因为this
指的是window
。
Dumping your own variables attached to window
is not possible in a clean way (some hacks still exist which consist in creating a fresh window
with an iframe
and compare it to the current window
, check this answer if you're interested)
现在,如果您希望this
引用当前 function 的词汇 scope,那么情况并非如此,您根本无法以编程方式检索它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.