Javascript:通过名称访问局部变量或闭包中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2336508/
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-08-22 23:50:30  来源:igfitidea点击:

Javascript: Get access to local variable or variable in closure by its name

javascriptfunctionvariableslocalclosures

提问by Ben Clayton

Possible Duplicate:
How can I access local scope dynamically in javascript?

可能的重复:
如何在 javascript 中动态访问本地范围?

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'].

大家好。
我们都知道您可以使用 [] 语法通过其名称访问 javascript 对象的属性.. 例如 ob['nameOfProperty']。

Can you do the same for a local variable? Another answer heresuggested the answer is to use window['nameOfVar']. However, this only worked for the poster as he was defining variables at window-level scope.

你能对局部变量做同样的事情吗?这里的另一个答案建议答案是使用 window['nameOfVar']。然而,这只适用于海报,因为他在窗口级范围内定义变量。

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?

我认为这在一般情况下必须是可能的,因为 Firefox 的 Firebug(我相信它是用 javascript 编写的)可以显示局部变量和闭包变量。是否有一些我不知道的隐藏语言功能?

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();

采纳答案by Bob

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).

我不知道 JavaScript 中内置什么来引用这样的局部变量(尽管可能应该考虑所有变量都是由字符串在内部引用的)。

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.

更新:我觉得没有办法像你想要的那样做这件事。在内部变量是声明性环境记录中的可变绑定。属性通过对象的环境记录绑定到它们作为属性的对象,但实际上有一种方法可以使用括号访问它们。不幸的是,无法以相同的方式访问声明性环境记录。

回答by PanJanek

Accessing the variable with window or any other global accessor won't work because the variable is not globally accessible. But you can use can use eval to evaluate any expression:

使用 window 或任何其他全局访问器访问变量将不起作用,因为该变量不可全局访问。但是您可以使用 can use eval 来评估任何表达式:

<script>
function test(){
   var j = 1; 
   alert(eval("j"));
}

test();
</script>

回答by ntownsend

No, because the variable is only accessible from within the execution contexts that contain the variable's scope.

不可以,因为变量只能从包含变量作用域的执行上下文中访问。

Put another way, the only way you can access jis if you are accessing it from something in the scope of test-- via an inner function, or whatever. This is because j, in a sense, doesn't exist to objects with a wider scope, like the global object. If it were otherwise, then variable names would have to globally unique.

换句话说,您可以访问的唯一方法j是从范围内的某些内容访问它test——通过内部函数或其他方式。这是因为j,从某种意义上说,不存在于范围更广的对象,例如全局对象。如果不是这样,那么变量名就必须全局唯一。

回答by Mic

What about:

关于什么:

<script>
    function Func(){
        var fn = arguments.callee;
        fn.j = 99;
        console.log(fn['j']);
    }
    Func();
    console.log(window['j']); //not global
    console.log(Func['j']); //but not private
</script>

回答by Tim Down

No, this isn't possible in general. JavaScript resolves identifiers inside a function using the scope chain; there's no single object that contains all the variables in scope, and the objects in the scope chain are inaccessible from JavaScript running in the page.

不,这在一般情况下是不可能的。JavaScript 使用作用域链解析函数内部的标识符;没有一个对象包含作用域中的所有变量,作用域链中的对象无法从页面中运行的 JavaScript 访问。