0

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.

Ritesh Kadmawala
  • 743
  • 9
  • 17

2 Answers2

2

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"]();
James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

Store your functions in an object as properties and retrieve them by name.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68