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

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

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


当前回答

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

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

其他回答

不要使用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);

两件事:

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

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

window.ClientSideValidations.forms.location_form

window.ClientSideValidations.forms['location_form']

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

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