[英]How to call functions by name in javascript where entire code is enclosed within some anonymous function
I want to write function that takes a function name as an argument and calls it. 我想编写一个以函数名作为参数并调用它的函数。 Normally i could do this using window[funcname]. 通常我可以使用window [funcname]来做到这一点。 However all my code is enclosed within an anonymous function and hence the namespace of the function is now window. 但是,我所有的代码都包含在一个匿名函数中,因此该函数的名称空间现在是window。 In this case how could i write this function. 在这种情况下,我该怎么写这个功能。
You could assign your functions to properties of an object: 您可以将功能分配给对象的属性:
var myFuncs = {
func1: function() {
//Do something
},
func2: function() {
//Do something else
}
};
You can then call func1
just like you suggest, but replacing window
with myFuncs
, like so: 然后,您可以像建议的那样调用func1
,但是用myFuncs
替换window
,如下所示:
myFuncs["func1"]();
将函数作为属性存储在对象中,然后按名称检索它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.