I am passing function A's or B's name in a parameter based on the situation to another function C. How can I call it in function C?
Asked
Active
Viewed 169 times
0
-
Yes, many duplicates, but no definitive answer so far (which is "bad idea, don't do that"). – georg Apr 11 '13 at 09:20
3 Answers
2
if A
is defined globally, then window["A"]()
. However, there's no need to do that in javascript. Just pass the function itself rather than its name:
function foo() {...}
// BAD
function callFunc(someName) { window[someName]() }
callFunc("foo")
// GOOD
function callFunc(someFunc) { someFunc() }
callFunc(foo)

georg
- 211,518
- 52
- 313
- 390
2
You could assign the functions to properties of an object. Then in your executing function reference the property by name given the parameter passed to the function.
var myFuncs = {
a: function(){
alert("Hello");
},
b: function(){
alert("Goodbye");
}
};
function execute(name){
myFuncs[name]();
}
execute("a");
execute("b");
Working Example http://jsfiddle.net/ud6BS/

Kevin Bowersox
- 93,289
- 19
- 159
- 189