【问题标题】:How do I pass the name of a function as a parameter then reference that function later?如何将函数的名称作为参数传递,然后稍后引用该函数?
【发布时间】:2012-08-31 15:20:51
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery function parameters parameter-passing


    【解决方案1】:

    在 runTests 中,使用如下代码:

    window[functionName]();
    

    不过,请确保 testMath 在全局范围内。

    【讨论】:

      【解决方案2】:

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

      runTheTest(yourFunction);
      
      
      function runTheTest(f)
      {
        f();
      }
      

      否则,您可以调用

      window[f]();
      

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

      【讨论】:

        【解决方案3】:

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

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

        更多信息here.

        【讨论】:

        • 我可以看到哪里可以更干净,但不幸的是 apply 在我的场景中不起作用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多