我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?

根据具体情况,我可能还需要将各种参数传递到方法中。

一些函数可以采用namespace.namespace.function(args[…])的形式。


这个其他问题的答案向您展示了如何做到这一点:Javascript相当于Python的locals()?

基本上,你可以说

window["foo"](arg1, arg2);

或者像其他人建议的那样,你可以使用eval:

eval(fname)(arg1, arg2);

虽然这是非常不安全的,除非你完全确定你在评估什么。


两件事:

避免评估,这是非常危险和缓慢的 其次,函数在哪里并不重要,“全局性”是无关紧要的。x.y.foo()可以通过x.y(“foo”)()或x (y)(“foo”)()甚至窗口[x] [y](“foo”)()。你可以像这样无限地链。


不要使用eval,除非你绝对没有其他选择。

如前所述,使用这样的东西是最好的方法:

window["functionName"](arguments);

然而,这对命名空间函数不起作用:

window["My.Namespace.functionName"](arguments); // fail

你可以这样做:

window["My"]["Namespace"]["functionName"](arguments); // succeeds

为了让这更容易,并提供一些灵活性,这里有一个便利函数:

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);
}

你可以这样称呼它:

executeFunctionByName("My.Namespace.functionName", window, arguments);

注意,你可以在任何你想要的上下文中传递,所以这将和上面一样:

executeFunctionByName("Namespace.functionName", My, arguments);

我只是想发布一个稍微改变了的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);
}

你只需要通过window[<方法名>]将字符串转换为指针。 例子:

var function_name = "string";
function_name = window[function_name];

现在你可以把它当做一个指针。


也有一些非常有用的方法。

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
};

关于杰森和亚历克斯的帖子还有一个细节。我发现向上下文添加默认值很有帮助。只要写上context = context == undefined?窗口:上下文;在函数的开始。您可以将window更改为您首选的上下文,这样您就不需要每次在默认上下文中调用this时都传入相同的变量。


如果你想用window["functionName"]调用一个对象的函数而不是全局函数。你可以这样做;

var myObject=new Object();
myObject["functionName"](arguments);

例子:

var now=new Date();
now["getFullYear"]()

你能不能不要这样做:

var codeToExecute = "My.Namespace.functionName()";
var tmpFunc = new Function(codeToExecute);
tmpFunc();

您还可以使用此方法执行任何其他JavaScript。


所有答案都假设函数可以通过全局作用域(窗口)访问。然而,OP并没有做出这样的假设。

如果函数存在于局部作用域(即闭包)中,并且没有被其他局部对象引用,那么运气就不好了:你必须使用eval() AFAIK,参见 在javascript中动态调用局部函数


这对我来说很管用:

var command = "Add";
var tempFunction = new Function("Arg1","Arg2", "window." + command + "(Arg1,Arg2)");
tempFunction(x,y);

我希望这有用。


为了补充Jason Bunting的答案,如果你正在使用nodejs或其他东西(这在dom js中也有效),你可以使用this而不是window(记住:eval是邪恶的:

this['fun'+'ctionName']();

小心! !

在JavaScript中应该尽量避免通过字符串调用函数,原因有两个:

原因1:一些代码混淆器会破坏你的代码,因为它们会改变函数名,使字符串无效。

原因2:维护使用这种方法的代码要困难得多,因为定位字符串调用的方法的用法要困难得多。


惊讶地看到没有提到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);

在我的代码中有一个非常相似的东西。 我有一个服务器生成的字符串,其中包含一个函数名,我需要作为第三方库的回调传递。所以我有一个代码,接受字符串并返回一个指向函数的“指针”,如果没有找到,则为空。

我的解决方案非常类似于“Jason Bunting的非常有用的功能”*,尽管它不能自动执行,而且上下文总是在窗口上。但这是很容易修改的。

希望这能对别人有所帮助。

/**
 * Converts a string containing a function or object method name to a function pointer.
 * @param  string   func
 * @return function
 */
function getFuncFromString(func) {
    // if already a function, return
    if (typeof func === 'function') return func;

    // if string, try to find function or method of object (of "obj.func" format)
    if (typeof func === 'string') {
        if (!func.length) return null;
        var target = window;
        var func = func.split('.');
        while (func.length) {
            var ns = func.shift();
            if (typeof target[ns] === 'undefined') return null;
            target = target[ns];
        }
        if (typeof target === 'function') return target;
    }

    // return null if could not parse
    return null;
}

所以,就像其他人说的,最好的选择是:

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(“家伙”);


我认为一种优雅的方法是在哈希对象中定义函数。然后,您可以使用字符串从哈希中引用这些函数。如。

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](参数);


在ES6中,你可以通过名称访问类方法:

class X {
  method1(){
    console.log("1");
  }
  method2(){
    this['method1']();
    console.log("2");
  }
}
let x  = new X();
x['method2']();

输出将是:

1
2

我忍不住要提到另一个技巧,如果你有一个未知数量的参数,这些参数也作为包含函数名的字符串的一部分被传递,那么这个技巧是有用的。例如:

Var annoyingstring = 'call_my_func(123, true, "blah")';

如果你的Javascript运行在HTML页面上,你所需要的只是一个看不见的链接;您可以向onclick属性传递一个字符串,然后调用click方法。

<a href="#" id="link_secret"><!——invisible——></a>

$('#link_secret').attr('onclick', annoyingstring);
$('#link_secret').click();

或者在运行时创建<a>元素。


不使用eval('function()'),您可以使用new function(strName)创建一个新函数。下面的代码是使用FF, Chrome, IE测试的。

<html>
<body>
<button onclick="test()">Try it</button>
</body>
</html>
<script type="text/javascript">

  function test() {
    try {    
        var fnName = "myFunction()";
        var fn = new Function(fnName);
        fn();
      } catch (err) {
        console.log("error:"+err.message);
      }
  }

  function myFunction() {
    console.log('Executing myFunction()');
  }

</script>

最简单的方法是像has元素一样访问它

window.ClientSideValidations.forms.location_form

window.ClientSideValidations.forms['location_form']

基本:

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

存在其他类型的函数类,看例子


谢谢你非常有用的回答。我在我的项目中使用了Jason Bunting的功能。

我扩展了它,使用一个可选的超时,因为设置超时的正常方式不会工作。请看abhishekisnot的问题

function executeFunctionByName(functionName, context, timeout /*, args */ ) { var args = Array.prototype.slice.call(arguments, 3); var namespaces = functionName.split("."); var func = namespaces.pop(); for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } var timeoutID = setTimeout( function(){ context[func].apply(context, args)}, timeout ); return timeoutID; } var _very = { _deeply: { _defined: { _function: function(num1, num2) { console.log("Execution _very _deeply _defined _function : ", num1, num2); } } } } console.log('now wait') executeFunctionByName("_very._deeply._defined._function", window, 2000, 40, 50 );


这里有几个executeByName函数,它们工作得很好,除非name包含方括号——这是我遇到的问题——因为我有动态生成的名称。因此,上述函数将失败的名称

小部件应用。[toggleFolders’‘872LfCHc] []

作为补救措施,我也考虑了这一点,也许有人会发现它很有用:

由CoffeeScript生成:

var executeByName = function(name, context) {
  var args, func, i, j, k, len, len1, n, normalizedName, ns;
  if (context == null) {
    context = window;
  }
  args = Array.prototype.slice.call(arguments, 2);
  normalizedName = name.replace(/[\]'"]/g, '').replace(/\[/g, '.');
  ns = normalizedName.split(".");
  func = context;
  for (i = j = 0, len = ns.length; j < len; i = ++j) {
    n = ns[i];
    func = func[n];
  }
  ns.pop();
  for (i = k = 0, len1 = ns.length; k < len1; i = ++k) {
    n = ns[i];
    context = context[n];
  }
  if (typeof func !== 'function') {
    throw new TypeError('Cannot execute function ' + name);
  }
  return func.apply(context, args);
}

为了更好的可读性检查CoffeeScript版本:

executeByName = (name, context = window) ->
    args = Array.prototype.slice.call(arguments, 2)
    normalizedName = name.replace(/[\]'"]/g, '').replace(/\[/g, '.')
    ns = normalizedName.split "."
    func = context
    for n, i in ns
        func = func[n]

    ns.pop()
    for n, i in ns
        context = context[n];
    if typeof func != 'function'
        throw new TypeError 'Cannot execute function ' + name
    func.apply(context, args)

你也可以在eval("functionname as string")中调用javascript函数。(eval是纯javascript函数)

function testfunc(){
    return "hello world";
}

$( document ).ready(function() {

     $("div").html(eval("testfunc"));
});

工作示例:https://jsfiddle.net/suatatan/24ms0fna/4/


以下是我对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
  */

  let t0 = () => { alert('red0') }
  var t1 = () =>{ alert('red1') }
  var t2 = () =>{ alert('red2') }
  var t3 = () =>{ alert('red3') }
  var t4 = () =>{ alert('red4') }
  var t5 = () =>{ alert('red5') }
  var t6 = () =>{ alert('red6') }

  function getSelection(type) {
    var evalSelection = {
      'title0': t0,
      'title1': t1,
      'title2': t2,
      'title3': t3,
      'title4': t4,
      'title5': t5,
      'title6': t6,
      'default': function() {
        return 'Default';
      }
    };
    return (evalSelection[type] || evalSelection['default'])();
  }
  getSelection('title1');

一个更面向对象的解决方案…


您所要做的就是使用上下文或定义函数驻留的新上下文。 你不局限于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。


由于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, ...);


下面是我的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


取决于你在哪里,你也可以使用:

this["funcname"]();
self["funcname"]();
window["funcname"]();
top["funcname"]();
globalThis["funcname"]();

或者,在nodejs中

global["funcname"]()

人们一直说eval是危险和邪恶的,因为它可以运行任何任意的代码。然而,如果您使用白名单方法使用eval,假设您知道所有可能需要提前运行的函数名,那么eval就不再是安全问题,因为输入不再是任意的。白名单是一种良好且常用的安全模式。这里有一个例子:

函数runDynamicFn(fnName,…args) { //也可以从一个严格控制的配置 const allowedFnNames = ['fn1', 'ns1.ns2.]fn3”、“ns4.fn4 '); 返回allowedFnNames.includes(fnName) ?eval(fnName)(…args): undefined; } //测试函数: 函数fn1(a) { Console.log ('fn1 called with', a) } runDynamicFn(“警报(“有你!”)”) runDynamicFn(“fn1”、“foo”)


我认为你不需要复杂的中间函数或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");

因为它使用的是属性访问,所以它将在最小化或混淆中存活下来,这与您在这里找到的一些答案相反。


下面是我最终为我的一个项目实现的一个健壮且可重用的解决方案。

一个FunctionExecutor构造函数

用法:

let executor = new FunctionExecutor();
executor.addFunction(two)
executor.addFunction(three)

executor.execute("one");
executor.execute("three");

显然,在项目中,所有需要按名称调用的函数的添加都是通过循环完成的。

函数Executor:

function FunctionExecutor() {
  this.functions = {};

  this.addFunction = function (fn) {
    let fnName = fn.name;
    this.functions[fnName] = fn;
  }

  this.execute = function execute(fnName, ...args) {
    if (fnName in this.functions && typeof this.functions[fnName] === "function") {
      return this.functions[fnName](...args);
    }
    else {
      console.log("could not find " + fnName + " function");
    }
  }

  this.logFunctions = function () {
    console.log(this.functions);
  }
}

使用示例:

function two() {
  console.log("two"); 
}

function three() {
  console.log("three");
}

let executor = new FunctionExecutor();
executor.addFunction(two)
executor.addFunction(three)

executor.execute("one");
executor.execute("three");

你可以把你的函数名放在一个Array对象中,然后调用每个函数对应的数组键来执行它,DEMO:

function captchaTest(msg){
    let x = Math.floor(Math.random()*(21-1)) +1;
    let y = Math.floor(Math.random()*(11-1)) +1;
    let sum = function(){
        return x+y;
    }
    let sub = function(){
        if (y > x){
            let m = y;
            y = x;
            x = m;
            console.log(x,y,m,'--')
        }
        return x-y;
    }
    let mul = function(){
        return x*y;
    } 
    let OParr = [sum(), sub(), mul()]; 
    let OP = Math.floor(Math.random()*OParr.length);      
    let s = OParr[OP]; //!!! HERE !!! is the call as array element
    switch(OP){
        case 0:
            opra = '+';
            break;
        case 1:
            opra = '━';
            break;
        default:
            opra = '✖';
    }
    let msg2 = 'Answer the following question to continue:'
    let p = prompt(msg+' '+msg2+'\n'+'What is the result of '+x+opra+y+' ?','')
    console.log(s,p,OP)
    if (s == p){
        alert ('Wow, Correct Answer!')
        return true;
    }
    else{
        alert('Sorry, the answer is not correct!')
        return false;
    }
}

  const myFnCollection = {
    myFnStringName: function(args) {}
  };

  let fn = 'myFnStringName';

  // 1. Recommended
  if (typeof window[fn] === 'function') {
    window[fn](args);
  }

  // 2. Recommended
  if (typeof myFnCollection[fn] === 'function') {
    myFnCollection[fn](args);
  }

  // 3. Eval is evil ;)
  if (typeof eval(fn) === 'function') {
    eval(fn)(args);
  }