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
}
4

3 に答える 3

6

関数名を文字列として必要ですか? そうでない場合は、次のように関数を渡すことができます。

runTheTest(yourFunction);


function runTheTest(f)
{
  f();
}

それ以外の場合は、呼び出すことができます

window[f]();

「グローバル」スコープ内のすべてが実際にはウィンドウ オブジェクトの一部であるため、これは機能します。

于 2012-09-06T18:36:09.697 に答える
2

runTests内で、次のようなものを使用します。

window[functionName]();

testMathただし、グローバルスコープで確認してください。

于 2012-09-06T18:34:11.263 に答える
1

パラメータを渡すときは、適用/呼び出しアプローチを使用することを好みます。

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

詳細はこちら

于 2012-09-06T18:40:49.157 に答える