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

查看:27
本文介绍了当我将其名称作为字符串时如何执行 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

你可以这样做:

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天全站免登陆