2012-09-06 175 views
1

我想将函数“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 
} 

回答

6

你需要函数名称作为字符串吗?如果没有,你可以传递给函数是这样的:

runTheTest(yourFunction); 


function runTheTest(f) 
{ 
    f(); 
} 

否则,您可以拨打

window[f](); 

这工作,因为一切都在“全球”范围实际上是window对象的一部分。

2

内runTests,使用这样的:

window[functionName](); 

确保testMath在全球范围内,虽然。

1

我preffer使用应用/呼叫的方式传递PARAMS时:

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

更多信息here

+0

我可以看到这可能会更清洁,但不幸的是,适用于我的方案不起作用。 – silvster27

相关问题