我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
当前回答
由于eval()是邪恶的,而new Function()不是最有效的方法来实现这一点,这里有一个快速的JS函数,从它的字符串名称返回函数。
适用于命名空间的函数 在null/undefined字符串的情况下回退到null函数 如果没有找到函数,则回退到null函数
function convertStringtoFunction(functionName){ var nullFunc = function(){}; // Fallback Null-Function var ret = window; // Top level namespace // If null/undefined string, then return a Null-Function if(functionName==null) return nullFunc; // Convert string to function name functionName.split('.').forEach(function(key){ ret = ret[key]; }); // If function name is not available, then return a Null-Function else the actual function return (ret==null ? nullFunc : ret); }
用法:
convertStringtoFunction("level1.midLevel.myFunction")(arg1, arg2, ...);
其他回答
所以,就像其他人说的,最好的选择是:
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(“家伙”);
我只是想发布一个稍微改变了的Jason Bunting非常有用的函数。
首先,我通过向slice()提供第二个参数简化了第一个语句。最初的版本在除IE之外的所有浏览器中都运行良好。
其次,我在return语句中用context替换了它;否则,在执行目标函数时,它总是指向window。
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
取决于你在哪里,你也可以使用:
this["funcname"]();
self["funcname"]();
window["funcname"]();
top["funcname"]();
globalThis["funcname"]();
或者,在nodejs中
global["funcname"]()
基本:
var namefunction = 'jspure'; // String
function jspure(msg1 = '', msg2 = '') {
console.log(msg1+(msg2!=''?'/'+msg2:''));
} // multiple argument
// Results ur test
window[namefunction]('hello','hello again'); // something...
eval[namefunction] = 'hello'; // use string or something, but its eval just one argument and not exist multiple
存在其他类型的函数类,看例子
在ES6中,你可以通过名称访问类方法:
class X {
method1(){
console.log("1");
}
method2(){
this['method1']();
console.log("2");
}
}
let x = new X();
x['method2']();
输出将是:
1
2