我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
当前回答
下面是我的Es6方法,它允许你调用你的函数的名字作为字符串或它的函数名,也允许你传递不同数量的参数给不同类型的函数:
function fnCall(fn, ...args) { let func = (typeof fn =="string")?window[fn]:fn; if (typeof func == "function") func(...args); else throw new Error(`${fn} is Not a function!`); } function example1(arg1){console.log(arg1)} function example2(arg1, arg2){console.log(arg1 + " and " + arg2)} function example3(){console.log("No arguments!")} fnCall("example1", "test_1"); fnCall("example2", "test_2", "test3"); fnCall(example3); fnCall("example4"); // should raise an error in console
其他回答
所以,就像其他人说的,最好的选择是:
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 / Alex Nazarov的精彩回答的贡献,其中包括Crashalot要求的错误检查。
鉴于这个(做作的)序言:
a = function( args ) {
console.log( 'global func passed:' );
for( var i = 0; i < arguments.length; i++ ) {
console.log( '-> ' + arguments[ i ] );
}
};
ns = {};
ns.a = function( args ) {
console.log( 'namespace func passed:' );
for( var i = 0; i < arguments.length; i++ ) {
console.log( '-> ' + arguments[ i ] );
}
};
name = 'nsa';
n_s_a = [ 'Snowden' ];
noSuchAgency = function(){};
然后执行如下函数:
function executeFunctionByName( functionName, context /*, args */ ) {
var args, namespaces, func;
if( typeof functionName === 'undefined' ) { throw 'function name not specified'; }
if( typeof eval( functionName ) !== 'function' ) { throw functionName + ' is not a function'; }
if( typeof context !== 'undefined' ) {
if( typeof context === 'object' && context instanceof Array === false ) {
if( typeof context[ functionName ] !== 'function' ) {
throw context + '.' + functionName + ' is not a function';
}
args = Array.prototype.slice.call( arguments, 2 );
} else {
args = Array.prototype.slice.call( arguments, 1 );
context = window;
}
} else {
context = window;
}
namespaces = functionName.split( "." );
func = namespaces.pop();
for( var i = 0; i < namespaces.length; i++ ) {
context = context[ namespaces[ i ] ];
}
return context[ func ].apply( context, args );
}
将允许您通过存储在字符串中的名称(命名空间或全局)调用javascript函数,带或不带参数(包括数组对象),为遇到的任何错误提供反馈(希望能够捕获它们)。
示例输出显示了它是如何工作的:
// calling a global function without parms
executeFunctionByName( 'a' );
/* OUTPUT:
global func passed:
*/
// calling a global function passing a number (with implicit window context)
executeFunctionByName( 'a', 123 );
/* OUTPUT:
global func passed:
-> 123
*/
// calling a namespaced function without parms
executeFunctionByName( 'ns.a' );
/* OUTPUT:
namespace func passed:
*/
// calling a namespaced function passing a string literal
executeFunctionByName( 'ns.a', 'No Such Agency!' );
/* OUTPUT:
namespace func passed:
-> No Such Agency!
*/
// calling a namespaced function, with explicit context as separate arg, passing a string literal and array
executeFunctionByName( 'a', ns, 'No Such Agency!', [ 007, 'is the man' ] );
/* OUTPUT:
namespace func passed:
-> No Such Agency!
-> 7,is the man
*/
// calling a global function passing a string variable (with implicit window context)
executeFunctionByName( 'a', name );
/* OUTPUT:
global func passed:
-> nsa
*/
// calling a non-existing function via string literal
executeFunctionByName( 'n_s_a' );
/* OUTPUT:
Uncaught n_s_a is not a function
*/
// calling a non-existing function by string variable
executeFunctionByName( n_s_a );
/* OUTPUT:
Uncaught Snowden is not a function
*/
// calling an existing function with the wrong namespace reference
executeFunctionByName( 'a', {} );
/* OUTPUT:
Uncaught [object Object].a is not a function
*/
// calling no function
executeFunctionByName();
/* OUTPUT:
Uncaught function name not specified
*/
// calling by empty string
executeFunctionByName( '' );
/* OUTPUT:
Uncaught is not a function
*/
// calling an existing global function with a namespace reference
executeFunctionByName( 'noSuchAgency', ns );
/* OUTPUT:
Uncaught [object Object].noSuchAgency is not a function
*/
您所要做的就是使用上下文或定义函数驻留的新上下文。 你不局限于window["f"]();
下面是我如何为一些REST服务使用一些动态调用的示例。
/*
Author: Hugo Reyes
@ www.teamsrunner.com
*/
(function ( W, D) { // enclose it as self invoking function to avoid name collisions.
// to call function1 as string
// initialize your FunctionHUB as your namespace - context
// you can use W["functionX"](), if you want to call a function at the window scope.
var container = new FunctionHUB();
// call a function1 by name with one parameter.
container["function1"](' Hugo ');
// call a function2 by name.
container["function2"](' Hugo Leon');
// OO style class
function FunctionHUB() {
this.function1 = function (name) {
console.log('Hi ' + name + ' inside function 1')
}
this.function2 = function (name) {
console.log('Hi' + name + ' inside function 2 ')
}
}
})(window, document); // in case you need window context inside your namespace.
如果你想从一个字符串生成整个函数,那是另一个答案。 另外请注意,你不局限于一个单一的命名空间,如果你的命名空间存在于my.name.space.for.functions.etc.etc.etc,那么你的命名空间的最后一个分支包含了my.name.space.for.functions.etc.etc["function"]();
希望能有所帮助。 H。
我认为一种优雅的方法是在哈希对象中定义函数。然后,您可以使用字符串从哈希中引用这些函数。如。
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](参数);
我只是想发布一个稍微改变了的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);
}