使用字符串变量的值调用Javascript函数的方法? [英] Ways to call a Javascript function using the value of a string variable?

查看:89
本文介绍了使用字符串变量的值调用Javascript函数的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数foo() ){
alert('foo');
}

var test ='foo';

window [test](); //这是调用foo()

这是可接受的方式吗?还是有更好的方法?任何需要担心的跨浏览器问题?

解决方案

看起来对我来说很好。我可能会创建一个简单的助手函数,如下所示:

$ p $ function runFunction(name,arguments)
{
var fn = window [name];
if(typeof fn!=='function')
return;

fn.apply(window,arguments);
}

//如果你有以下函数

函数foo(msg)
{
alert(msg);
}

//你可以称它为

runFunction('foo',['test']); //提醒测试。


I've seen this technique for calling a Javascript function based on the value of a string variable.

function foo() {
    alert('foo');
}

var test = 'foo';

window[test]();  //This calls foo()

Is this the accepted way to do it or is there a better way? Any cross-browser issues to worry about?

解决方案

Looks fine to me. I would probably create a simple helper function like following:

function runFunction(name, arguments)
{
    var fn = window[name];
    if(typeof fn !== 'function')
        return;

    fn.apply(window, arguments);
}

//If you have following function

function foo(msg)
{
    alert(msg);
}

//You can call it like

runFunction('foo', ['test']); //alerts test.

这篇关于使用字符串变量的值调用Javascript函数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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