我可以使用变量的值来启动一个函数吗? [英] Can I use the value of a variable to initiate a function?

查看:99
本文介绍了我可以使用变量的值来启动一个函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

调用一个名为变量的JavaScript函数


我想使用变量的值作为调用来启动一个函数,但我不确定它是否可能?



说我有:

 函数myFunction(){
//做某事
}

var functionName =myFunction;
functionName(); //这个应该运行名为myFunction的函数

这是可以完成的吗?

解决方案

您可以做几件事:

  //如果函数在全局作用域中:

window [myFunction]();
//或
var functionName =myFunction;
window [functionName]();

或者维护您自己的地图:

 var functions = {
myFunction:function(){
...
},
...
myOtherFunction:function (){
...
}
};

然后执行以下任一操作:

  functions.myFunction(); //将工作
functions [myFunction](); //也会起作用;

var functionName =myFunction;
functions [functionName](); //也可以工作

当然,您可以使用 eval $ b $ pre $ e $(eval(functionName +());

但是 eval 很危险,我不要推荐它。



根据您的小提琴

您的右侧左侧函数已在匿名函数的本地范围内定义。这意味着它们是全局窗口对象的不是的一部分。您应该使用上面描述的第二种方法(构建您自己的地图):

  var directions = {
right:函数(){
...
},
left:function(){
...
}
...
};

var direction =right;
方向[方向]();


Possible Duplicate:
Calling a JavaScript function named in a variable

I want to use the value of a variable as the call to initiate a function, but I'm not sure if it is possible?

say I have:

function myFunction(){
    // Do something
}

var functionName = "myFunction";
functionName(); // This should run the function named myFunction

Is this something that can be done?

解决方案

You could do a few things:

//if the function is in the global scope:

window["myFunction"](); 
//or
var functionName = "myFunction";
window[functionName]();

Or maintain your own map:

var functions = {
    myFunction: function() {
        ...
    },
    ...
    myOtherFunction: function() {
        ...
    }
};

Then either of the following will work:

functions.myFunction(); //will work
functions["myFunction"](); //will also work;

var functionName = "myFunction";
functions[functionName](); //also works

Of course, you can use eval:

eval(functionName + "()");

But eval is dangerous and I don't recommend it.

Based on your fiddle

Your right and left functions have been defined in the local scope of an anonymous function. This means that they are not part of the global window object. You should use the second method I described above (constructing your own map):

var directions = {
    right: function() {
        ...
    },
    left: function() {
        ...
    }
    ...
};

var direction = "right";
directions[direction]();

这篇关于我可以使用变量的值来启动一个函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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