如果要动态使用全局函数和变量,可以使用:
window[functionName](window[varName]);
Run Code Online (Sandbox Code Playgroud)
是否可以对本地范围内的变量执行相同的操作?
这段代码工作正常,但目前使用eval,我正在考虑如何做到这一点.
var test = function(){
//this = window
var a, b, c; //private variables
var prop = function(name, def){
//this = window
eval(name+ ' = ' + (def.toSource() || undefined) + ';');
return function(value){
//this = test object
if ( !value) {
return eval('(' + name + ')');
}
eval(name + ' = value;')
return this;
};
};
return {
a:prop('a', 1),
b:prop('b', 2),
c:prop('c', 3),
d:function(){
//to show that they are accessible via to methods
return …Run Code Online (Sandbox Code Playgroud) 可能重复:
如何在javascript中动态访问本地范围?
大家好.
我们都知道您可以使用[]语法通过它的名称访问javascript对象的属性.例如ob ['nameOfProperty'].
你能为局部变量做同样的事吗?这里的另一个答案表明答案是使用window ['nameOfVar'].然而,这只适用于海报,因为他在窗口级范围内定义变量.
我认为这通常是可能的,因为Firefox的Firebug(我认为是用javascript编写的)可以显示本地和闭包变量.是否有一些我不知道的隐藏语言功能?
具体来说,这就是我想要做的事情:
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();
Run Code Online (Sandbox Code Playgroud) 基本上这是一个如何访问本地范围处理程序的问题.我试图为全局变量定义实现类似的东西,如:
window['newObject'] = "some string";
alert(newObject);
Run Code Online (Sandbox Code Playgroud)
但对于当地范围.现在我只有解决方案是使用evals:
eval("var newObject='some string'");
Run Code Online (Sandbox Code Playgroud)
但这是一个非常丑陋的解决方案......最好的方法就是在window []解决方案中使用一些本地范围的引用,但我从来没有听说过任何对本地范围的引用......有什么想法吗?
示例如下:
function x(arg)
{
localScope[arg.name]=arg.value;
alert(sex);
}
x({name:"sex", value:"Male"});
Run Code Online (Sandbox Code Playgroud)