Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
动态命名和实现javascript函数体_Javascript_Function_Call_Dynamically Generated - Fatal编程技术网

动态命名和实现javascript函数体

动态命名和实现javascript函数体,javascript,function,call,dynamically-generated,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]) === "functio

为了简单起见,我包含了一个脚本,可以根据函数名动态调用函数:

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);
}
但是函数say_helloworld的代码是以静态方式编写的。我想要一些像:

var function_implementation = 'function say_'+foo+bar+
    '(the_world){alert("Hello " + the_world);}';
eval(function_implementation);
但不使用eval()。还有一种更丑陋的方法:通过AJAX调用获取函数


您能找到更好的方法吗?

您可以使用内联函数表达式:

window['say_'+foo+bar]= function(the_world) {
    alert('Hello '+the_world);
};
然而,使用动态命名变量几乎没有什么好的理由。将函数存储在单独的查找对象中:

var says= {
    helloworld: function(the_world) {
        alert('Hello '+the_world);
    },
    somethingelse: function(otherthing) {
        alert('Something else with '+otherthing);
    }
};
says[somevar]('potatoes');

如果要在不使用
eval
的情况下动态生成函数,可以使用构造函数

Function([arg1[, arg2[, ... argN]],] functionBody)
这样你就可以做像这样的事情

var func = new Function('message', 'alert("Hello, " + message);')
func('world!');
有关更多说明,请参阅

干杯


注意:我以前从未使用过这种方法,也从未使用过Function()构造函数。因此,我不知道这是否有任何其他缺点。

您可以使用超时来解释代码,但它可能在内部使用eval,因此不确定您是否需要它

fText = 'function test(a){alert(a);}';
setTimeout(fText,0);

但是在调用它之前需要几毫秒的时间。

@altvali它包含在ECMA-262第三版()中,这是Javascript 1.5的基础。根据维基百科()的说法,即使是IE5.5也应该理解这一点。