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

标签 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
}

最佳答案

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

runTheTest(yourFunction);


function runTheTest(f)
{
  f();
}

否则,你可以调用

window[f]();

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

关于javascript - 如何将函数名称作为参数传递,然后再引用该函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12306283/

相关文章:

javascript - 列出开放有限有向图中给定节点的所有可能路径

javascript - 将键/值对附加到Leaflet中的L.Control.layer

javascript - 从 Vue.js 组件数据中导入的辅助类调用函数

javascript - 使用 jquery AJAX 提交表单

c++ - 奇怪的功能

javascript - Ajax 成功功能无法正常工作

javascript - 当单击页面中的任何按钮时,将在使用 Jquery-File-Upload 时打开文件对话框

jquery - 单击然后返回时更改 div 宽度

function - 在语言层面, `ccall` 到底是什么?

函数中的 bash 参数解析