您可以使用 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() 时定义了一个匿名函数。
(显然这是一个过于简单的示例,但我希望您能看到它如何满足您的实际需求。)