-1

I am trying to pass a function name and its parameters as parameter and call it

Here is the code

$(document).ready(function(){
    runfn(getUserName,paramValue);
});

function runfn(fnName,param){
    fnName(param);
};

function getUserName(userId){
    alert(userId);
};

Feel free to edit this fiddle

i want to call function with parameters using this method

Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150
  • 2
    Pass the name, not a string containing the name. – Pointy May 18 '15 at 14:07
  • You should probably specify some sort of use case for this, because a lot of people are missing that you want to include parameters in your function call. There are a number of ways you could do that, of course, but I'm curious as to why you wouldn't just use a standard function callback like [this](http://jsfiddle.net/96mhqLfp/3/). – thewatcheruatu May 18 '15 at 14:17

2 Answers2

3

If you want that you might need to use the eval(). Be aware that this has potential security issues with it. You can also just call the function on the global window object: window[fnName]();

Additionally, in your case, you can also just pass the reference to the function. Meaning, do not specify the function name as a string, but just as a function.

callMe(functionToCall);

function callMe(fn){
    fn();
}

function functionToCall(){
    alert('Called!');
}
Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
1

Well you need to pass it as function name and not as string

DEMO HERE

Just a sample code where changes needed:

$(document).ready(function(){
alert("loaded");
    runfn(test);
});

UPDATE:

Just pass parameter in the phase where you are calling the function as below:

UPDATED DEMO

$(document).ready(function(){
    alert("loaded");
    runfn(test);
});

function runfn(fnName){
    alert(fnName);
    fnName('name');
};

function test(name){
     alert(name);
};
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200