Javascript:通过名称访问闭包中的局部变量或变量 [英] Javascript: Get access to local variable or variable in closure by its name
问题描述
大家好。
我们都知道,你可以使用[]语法访问javascript对象的属性。例如ob ['nameOfProperty']。
Hi all.
We all know that you can access a property of a javascript object by it's name using the [] syntax.. e.g. ob['nameOfProperty'].
你能为局部变量做同样的事吗?另一个回答这里建议的答案是使用window [' nameOfVar']。但是,这只适用于海报,因为他正在窗口级范围定义变量。
Can you do the same for a local variable? Another answer here suggested the answer is to use window['nameOfVar']. However, this only worked for the poster as he was defining variables at window-level scope.
我假设这一定是可能的,因为Firefox的Firebug相信是用javascript写的)可以显示局部变量和闭包变量。有没有一些隐藏的语言功能,我不知道?
I assume that this must be possible in general, as Firefox's Firebug (which I believe is written in javascript) can show local and closure variables. Is there some hidden language feature I'm not aware of?
具体来说,这里是我想做的:
Specifically, here's what I want to do:
var i = 4;
console.log(window['i']); // this works..
function Func(){
var j = 99;
// try to output the value of j from its name as a string
console.log(window['j']); // unsurprisingly, this doesn't work
}
Func();
推荐答案
引用局部变量类似(虽然可能应考虑所有变量内部引用字符串)。
I'm not aware of anything built into JavaScript to reference local variables like that (though there probably should be considering all variables are internally referenced by strings).
我建议保持所有的变量在一个对象,如果你真的需要通过字符串访问:
I'd suggest keeping all your variables in an object if you really need to access by string:
var variables = {
"j": 1
};
alert(variables["j"]);
更新:这种错误我没有办法像你想要的那样。内部变量是声明环境记录中的可变绑定。属性绑定到对象,它们是通过对象的环境记录的属性,但实际上有一种方法使用括号访问它们。不幸的是,没有办法以同样的方式访问声明式环境记录。
Update: It kind of bugs me that there's no way to do this like you want. Internally the variable is a mutable binding in the declarative environment records. Properties are bound to the object they're a property of through the object's environment records, but there's actually a way to access them using brackets. Unfortunately, there's no way to access the declarative environment records the same way.
这篇关于Javascript:通过名称访问闭包中的局部变量或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!