Javascript:可以通过变量将函数命令传递给另一个函数

Javascript: Possible to pass function commands to another function via a variable?

本文关键字:函数 另一个 命令 Javascript 可以通过 变量      更新时间:2023-09-26

好的,希望这能得到正确的理解。我正在构建一个通用的javascript函数,它将构建一个菜单,然后还构建每个菜单项将调用的函数。为此,我需要为每个选项传递一个要调用的命令列表。

例如:

var thecall = 'alert("hi, this works");';
function myfunction(thecall)
{
  //In here I want to excute whatever commands is listed in variable thecall
 .....
}

我确信这样做完全是愚蠢的,但我不知道该怎么做。

基本上,我需要我的函数在可变的基础上执行其他函数。

谢谢!!

我更喜欢向您展示如何使用它。

var thecall = function(name){alert("hi " + name + ", this works");};
function myFunction(function_ref)
{
  function_ref('Mark');
}
myFunction(thecall);

您可以使用eval()执行任意的JavaScript字符串,但这不是适合您的最佳解决方案(它几乎从来都不是最佳解决方案)。

JavaScript中的函数本身就是对象,这意味着你可以在多个变量中存储对同一函数的多个引用,或者将函数引用作为参数传递等等

var thecall = function() {
   alert("hi, this works");
};
function myfunction(someFunc)  {
   someFunc();    // call the function that was passed
}
myfunction(thecall);   // pass reference to thecall

请注意,在传递对thecall函数的引用时,没有括号,即说thecall而不是thecall():如果说myfunction(thecall()),它将立即调用thecall并传递它返回给myfunction的任何内容。在没有括号的情况下,它传递对thecall的引用,然后可以从myfunction中执行该引用。

在你谈论菜单项列表的情况下,每个菜单项都应该调用一个特定的函数,你可以这样做:

var menuItems = [];
function addMenuItem(menuText, menuFunction) {
   menuItems.push({ "menuText" : menuText, "menuFunction" : menuFunction });
}
function test1() {
   // do something
}
addMenuItem("Test 1", test1);
addMenuItem("Test 2", function() { alert("Menu 2"); });
// and to actually call the function associated with a menu item:
menuItems[1].menuFunction();

请注意,我添加的第二个菜单项在作为参数传递给addMenuItem()的地方定义了一个匿名函数。

(显然,这是一个过于简单化的例子,但我希望您能看到它如何满足您的实际需求。)

我认为您正在寻找eval函数。

var code= 'alert("hi, this works");';
eval(code);