View Full Version : Calling a function from a variable
docmattman
03-28-2006, 11:17 PM
Is it possible in javascript to assign a function name to a variable and use that variable to call the function, like this:
var funcToCall = "MyCustomFunction";
funcToCall();
Is there a way to accomplish something like this?
Brandoe85
03-29-2006, 12:08 AM
Curious, why would you need to do this instead of calling the function by it's name?
docmattman
03-29-2006, 12:22 AM
I guess the above code by itself is pointless, however there are instances where I would want to call a function that accomplishes general tasks, but then depending on the value that I pass the function, it will call whatever followup function I pass to it. Almost like a callback function. I am mainly a PHP programmer and I've run into MANY instances where this type of functionality is almost critical for me.
window["MyCustomFunction"]();
liorean
03-29-2006, 01:40 AM
Rather easy thing to do:var
oFn={
functionName0:function(){},
functionName1:function(){},
/.../
functionNamen:function(){}};
// Use this if you need to be able to call the functions as methods on
// an object. Otherwise you can just drop this function.
function callFunction(sFnName,aArgs,oObject){
if(!(sFnName in oFn))
throw new Error('Error: function "'+sFnName+'" does not exist.');
return oFn[sFnName].apply(oObject,aArgs);
}And then you can call the functions by a string like so:// Call the functions as methods on an object:
callFunction(sFnName,aArgs,oObject);
// Just call the functions:
oFn[sFnName](arg0, arg1, ... , argn);
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.