0

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?

Dhwani
  • 7,484
  • 17
  • 78
  • 139
  • 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 Answers3

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

Like this:

window[varName]()

assuming it is in global scope

If you have

function A() {}
function B() {}

then you can do

function C(parm) {
  parm();
}

if you call it with C(A) or C(B)

DEMO

mplungjan
  • 169,008
  • 28
  • 173
  • 236
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