Javascript:通过名称访问局部变量或闭包中的变量 [英] Javascript: Get access to local variable or variable in closure by its name

查看:26
本文介绍了Javascript:通过名称访问局部变量或闭包中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何在 javascript 中动态访问本地作用域?

大家好.
我们都知道您可以使用 [] 语法通过名称访问 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();

推荐答案

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆