silvster27
silvster27

Reputation: 1936

How do I pass the name of a function as a parameter then reference that function later?

I want to pass the name of a function "testMath" as a string into a wrapper function called "runTest" as a parameter. Then inside 'runTest' I would call the function that was passed. The reason I'm doing this is because we have a set of generic data that will populate into variables regardless of the test, then a specific test can be called, based on whatever the user wants to test. I am trying to do this using javascript/jquery. In reality the function is much more complex including some ajax calls, but this scenario highlights the basic challenge.

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

Upvotes: 1

Views: 182

Answers (3)

Marcelo Assis
Marcelo Assis

Reputation: 5194

I preffer to use apply/call approach when passing params:

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

More info here.

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116100

Do you need the function names as string? If not, you can just pass the function like this:

runTheTest(yourFunction);


function runTheTest(f)
{
  f();
}

Otherwise, you can call

window[f]();

This works, because everything in the 'global' scope is actually part of the window object.

Upvotes: 6

Some Guy
Some Guy

Reputation: 16190

Inside runTests, use something like this:

window[functionName]();

Make sure testMath in the global scope, though.

Upvotes: 2

Related Questions