For simplicity's sake, I've included a script that dynamically calls a function by its name:
var foo = "hello";
var bar = "world";
var function_name = "say_" + foo + bar;
// Since its name is being dynamically generated, always ensure your function actually exists
if (typeof(window[function_name]) === "function")
{
window[function_name](" World!");
}
else
{
throw("Error. Function " + function_name + " does not exist.");
}
function say_helloworld(the_word)
{
alert("Hello " + the_word);
}
But the function say_helloworld
's code is written in a static fashion. I would like something like:
var function_implementation = 'function say_'+foo+bar+
'(the_world){alert("Hello " + the_world);}';
eval(function_implementation);
but without using eval(). There's an even uglier approach: doing an AJAX call to get the function.
Can you see a better approach?