当我的名字作为字符串时,如何执行JavaScript函数 [英] How to execute a JavaScript function when I have its name as a string

查看:92
本文介绍了当我的名字作为字符串时,如何执行JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later?

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

Depending on the circumstances, I may need to pass various arguments into the method too.

某些函数可能采用 namespace.namespace.function(args [...])的形式。

Some of the functions may take the form of namespace.namespace.function(args[...]).

推荐答案

除非绝对,否则不要使用 eval 别无选择。

Don't use eval unless you absolutely, positively have no other choice.

正如已经提到的,使用这样的东西是最好的方法:

As has been mentioned, using something like this would be the best way to do it:

window["functionName"](arguments);

然而,这不适用于命名空间函数:

That, however, will not work with a namespace'd function:

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

这就是你要这样做的方式:

This is how you would do that:

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

为了使这更容易并提供一些灵活性,这里有一个便利功能:

In order to make that easier and provide some flexibility, here is a convenience function:

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

注意,你可以传入你想要的任何上下文,所以这将与上面相同:

Note, you can pass in whatever context you want, so this would do the same as above:

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

这篇关于当我的名字作为字符串时,如何执行JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆