Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想编写一个以函数名作为参数并调用它的函数。通常我可以使用 window[funcname] 来做到这一点。然而,我的所有代码都包含在一个匿名函数中,因此该函数的命名空间现在是 window。在这种情况下我怎么能写这个函数。
您可以将函数分配给对象的属性:
var myFuncs = { func1: function() { //Do something }, func2: function() { //Do something else } };
然后你可以func1像你建议的那样打电话,但用 替换window,myFuncs像这样:
func1
window
myFuncs
myFuncs["func1"]();
将您的函数作为属性存储在对象中并按名称检索它们。