gpt4 book ai didi

javascript - 动态命名和实现 javascript 函数的主体

转载 作者:搜寻专家 更新时间:2023-11-01 05:26:45 24 4
gpt4 key购买 nike

为了简单起见,我包含了一个通过名称动态调用函数的脚本:

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');

关于javascript - 动态命名和实现 javascript 函数的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3362302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com