e.g. someFunction() or someOtherFunction(‘text’, 101);
But what if you don’t know the name of function to be called and you know this only at runtime? Check following demo.
In above demo, click Call button. You can see an alert box with value ‘Happy New Year.!!’. Once you click the Call button, a function fnFooBar gets called. The name of the function and parameter is specified in first text box and the body of the function is in the text area.
Change the function parameter or add a new function in the textarea and call it from text box and then click Call button. You can see that the function gets called although it is not parsed by the browser.
Thus is you have a string whose value is the function name. You can call it by eval() function as follow:
var strFun = "someFunction"; var strParam = "this is the parameter"; //Create the function call from function name and parameter. var funcCall = strFun + "('" + strParam + "');"; //Call the function var ret = eval(funcCall);
It seems that there is a better way to do this without using
eval method. Thanks @Jerome for the comment.
window[functionName](parameters) to call any function
functionName. See below example:
var strFun = "someFunction"; var strParam = "this is the parameter"; //Create the function var fn = window[strFun]; //Call the function fn(strParam);