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.
Asked
Active
Viewed 97 times
0
-
1could you show us some code please? – Fabrizio Calderan Jun 01 '12 at 10:03
-
see my answer here. [call by name in javascript](https://stackoverflow.com/a/46090820/7771019) – Hugo R Sep 07 '17 at 08:10
2 Answers
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