简体   繁体   中英

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]. However all my code is enclosed within an anonymous function and hence the namespace of the function is now 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:

myFuncs["func1"]();

将函数作为属性存储在对象中,然后按名称检索它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM