Javascript 如何将函数名作为参数传递,然后在以后引用该函数?
我想将函数“testMath”的名称作为字符串传递给一个名为“runTest”的包装函数作为参数。然后在“runTest”中调用传递的函数。我这样做的原因是因为我们有一组通用数据,这些数据将填充到变量中,而不考虑测试,然后可以根据用户想要测试的内容调用特定的测试。我正在尝试使用javascript/jquery来实现这一点。实际上,函数要复杂得多,包括一些ajax调用,但是这个场景突出了基本的挑战Javascript 如何将函数名作为参数传递,然后在以后引用该函数?,javascript,jquery,function,parameters,parameter-passing,Javascript,Jquery,Function,Parameters,Parameter Passing,我想将函数“testMath”的名称作为字符串传递给一个名为“runTest”的包装函数作为参数。然后在“runTest”中调用传递的函数。我这样做的原因是因为我们有一组通用数据,这些数据将填充到变量中,而不考虑测试,然后可以根据用户想要测试的内容调用特定的测试。我正在尝试使用javascript/jquery来实现这一点。实际上,函数要复杂得多,包括一些ajax调用,但是这个场景突出了基本的挑战 //This is the wrapper that will trigger all the t
//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
}
在运行测试中,使用如下内容:
window[functionName]();
runTheTest(yourFunction);
function runTheTest(f)
{
f();
}
但是,请确保在全局范围内使用
testMath
。在运行测试中,请使用以下内容:
window[functionName]();
runTheTest(yourFunction);
function runTheTest(f)
{
f();
}
但是,请确保全局范围内的函数名是
testMath
。是否需要函数名作为字符串?如果没有,您可以这样传递函数:
window[functionName]();
runTheTest(yourFunction);
function runTheTest(f)
{
f();
}
否则,你可以打电话
window[f]();
这是可行的,因为“全局”范围内的所有内容实际上都是窗口对象的一部分。是否需要函数名作为字符串?如果没有,您可以这样传递函数:
window[functionName]();
runTheTest(yourFunction);
function runTheTest(f)
{
f();
}
否则,你可以打电话
window[f]();
这是可行的,因为“全局”范围内的所有内容实际上都是窗口对象的一部分。在传递参数时,我建议使用应用/调用方法:
...
myFunction.call(this, testQuery, testResult);
...
更多信息。我建议在传递参数时使用应用/调用方法:
...
myFunction.call(this, testQuery, testResult);
...
更多信息。我可以看到这在哪里更干净,但不幸的是,应用在我的场景中不起作用。我可以看到这在哪里更干净,但不幸的是,应用在我的场景中不起作用。