我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
当前回答
为了补充Jason Bunting的答案,如果你正在使用nodejs或其他东西(这在dom js中也有效),你可以使用this而不是window(记住:eval是邪恶的:
this['fun'+'ctionName']();
其他回答
我认为一种优雅的方法是在哈希对象中定义函数。然后,您可以使用字符串从哈希中引用这些函数。如。
var customObject = {
customFunction: function(param){...}
};
然后你可以调用:
customObject['customFunction'](param);
其中customFunction将是一个匹配对象中定义的函数的字符串。
更新
这个答案似乎对许多程序员有帮助,所以这里有一个更新版本。
在ES6中,你还可以使用计算属性名,这将允许你避免魔法字符串。
const FunctionNames = Object.freeze({ FirstFunction:“FirstFunction”, SecondFunction:“SecondFunction” }); … var customObject = { [functionname。FirstFunction]:函数(参数){…} [functionname。SecondFunction]:函数(参数){…} }; … customObject [FunctionNames.FirstFunction](参数);
惊讶地看到没有提到setTimeout。
运行一个不带参数的函数:
var functionWithoutArguments = function(){
console.log("Executing functionWithoutArguments");
}
setTimeout("functionWithoutArguments()", 0);
运行带参数的函数:
var functionWithArguments = function(arg1, arg2) {
console.log("Executing functionWithArguments", arg1, arg2);
}
setTimeout("functionWithArguments(10, 20)");
运行深度命名空间函数:
var _very = {
_deeply: {
_defined: {
_function: function(num1, num2) {
console.log("Execution _very _deeply _defined _function : ", num1, num2);
}
}
}
}
setTimeout("_very._deeply._defined._function(40,50)", 0);
所以,就像其他人说的,最好的选择是:
window['myfunction'](arguments)
就像Jason Bunting说的,如果你的函数名包含一个对象,它就不会工作:
window['myobject.myfunction'](arguments); // won't work
window['myobject']['myfunction'](arguments); // will work
下面是我的函数版本,它将按名称执行所有函数(包括对象与否):
My = { 代码:{ 是:{ Nice:函数(a, b){警报(a + "," + b);} } } }; Guy = function(){alert('awesome');} 函数executeFunctionByName(str, args) { Var arr = str.split('.'); Var fn = window[arr[0]]; For (var I = 1;I < arrr .length;我+ +) {fn = fn[arr[i]];} fn。应用(窗口,args); } executeFunctionByName(“my.code.is。Nice ', ['arg1', 'arg2']); executeFunctionByName(“家伙”);
也有一些非常有用的方法。
http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx
var arrayMaker = {
someProperty: 'some value here',
make: function (arg1, arg2) {
return [ this, arg1, arg2 ];
},
execute: function_name
};
我认为你不需要复杂的中间函数或eval,也不需要依赖像window这样的全局变量:
function fun1(arg) {
console.log(arg);
}
function fun2(arg) {
console.log(arg);
}
const operations = {
fun1,
fun2
};
operations["fun1"]("Hello World");
operations.fun2("Hello World");
// You can use intermediate variables, if you like
let temp = "fun1";
operations[temp]("Hello World");
它也可以使用导入的函数:
// mode.js
export function fun1(arg) {
console.log(arg);
}
export function fun2(arg) {
console.log(arg);
}
// index.js
import { fun1, fun2 } from "./mod";
const operations = {
fun1,
fun2
};
operations["fun1"]("Hello World");
operations["fun2"]("Hello World");
因为它使用的是属性访问,所以它将在最小化或混淆中存活下来,这与您在这里找到的一些答案相反。