如何将函数名称作为参数传递,然后再引用该函数?

时间:2012-09-06 18:32:37

标签: javascript jquery function parameters parameter-passing

我想将函数“testMath”的名称作为字符串传递给名为“runTest”的包装函数作为参数。然后在'runTest'里面我会调用传递的函数。我这样做的原因是因为我们有一组通用数据,无论测试如何都会填充到变量中,然后根据用户想要测试的内容调用特定的测试。我试图使用javascript / jquery来做到这一点。实际上,该功能要复杂得多,包括一些ajax调用,但这种情况突出了基本的挑战。

//This is the wrapper that will trigger all the tests to be ran
function performMytests(){
     runTest("testMath");    //This is the area that I'm not sure is possible
     runTest("someOtherTestFunction");
     runTest("someOtherTestFunctionA");
     runTest("someOtherTestFunctionB");
}


//This is the reusable function that will load generic data and call the function 
function runTest(myFunction){
    var testQuery = "ABC";
    var testResult = "EFG";
    myFunction(testQuery, testResult); //This is the area that I'm not sure is possible
}


//each project will have unique tests that they can configure using the standardized data
function testMath(strTestA, strTestB){
     //perform some test
}

3 个答案:

答案 0 :(得分:6)

您是否需要将函数名称作为字符串?如果没有,你可以像这样传递函数:

runTheTest(yourFunction);


function runTheTest(f)
{
  f();
}

否则,您可以致电

window[f]();

这很有效,因为“全局”范围内的所有内容实际上都是窗口对象的一部分。

答案 1 :(得分:2)

在runTests内部,使用以下内容:

window[functionName]();

确保testMath在全局范围内。

答案 2 :(得分:1)

我更喜欢在传递参数时使用apply / call方法:

...
myFunction.call(this, testQuery, testResult); 
...

更多信息here

相关问题