Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javascript - 我将其名称作为字符串时如何执行JavaScript函数(How to execute a JavaScript function when I have its name as a string)

I have the name of a function in JavaScript as a string.

(我有一个JavaScript函数的名称作为字符串。)

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.

(根据情况,我可能还需要将各种参数传递给该方法。)

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

(一些功能可能采用namespace.namespace.function(args[...]) 。)

  ask by Kieron translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(除非您绝对没有其他选择否则不要使用eval 。)

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

You would call it like so:

(您可以这样称呼它:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...