为简单起见,我包含了一个通过函数名动态调用函数的脚本:
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);
}
但是 functionsay_helloworld
的代码是以静态方式编写的。我想要类似的东西:
var function_implementation = 'function say_'+foo+bar+
'(the_world){alert("Hello " + the_world);}';
eval(function_implementation);
但不使用 eval()。还有一种更丑陋的方法:通过 AJAX 调用来获取函数。
你能看到更好的方法吗?