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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…