Val*_*sso 4 javascript function call dynamically-generated
为简单起见,我已经包含了一个脚本,它通过名称动态调用函数:
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);
}
Run Code Online (Sandbox Code Playgroud)
但函数say_helloworld的代码是以静态方式编写的.我想要像:
var function_implementation = 'function say_'+foo+bar+
'(the_world){alert("Hello " + the_world);}';
eval(function_implementation);
Run Code Online (Sandbox Code Playgroud)
但不使用eval().有一种更加丑陋的方法:进行AJAX调用以获得该功能.
你能看到更好的方法吗?
您可以使用内联函数表达式:
window['say_'+foo+bar]= function(the_world) {
alert('Hello '+the_world);
};
Run Code Online (Sandbox Code Playgroud)
但是,几乎没有充分的理由使用动态命名的变量.将函数存储在单独的查找对象中:
var says= {
helloworld: function(the_world) {
alert('Hello '+the_world);
},
somethingelse: function(otherthing) {
alert('Something else with '+otherthing);
}
};
says[somevar]('potatoes');
Run Code Online (Sandbox Code Playgroud)