1

I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.

I have a list of about 50 functions to be called such as :

globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)

My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):

var functionName = 'func'.concat('A');
globalClient.functionName

The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.

I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?

blueren
  • 2,730
  • 4
  • 30
  • 47
  • 1
    Use bracket notation `globalClient["func" + "B"]()` – Satpal Oct 24 '16 at 07:01
  • 2
    This is a dup of many, many other answers. – jfriend00 Oct 24 '16 at 07:02
  • 1
    take a look at this http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string. I hope this is what you are looking for – gkb Oct 24 '16 at 07:04
  • Thanks all. I tried searching here but I couldn't figure out the right terminology for it. I've got the answer. I'll mark it so that this question can be closed. – blueren Oct 24 '16 at 07:13

2 Answers2

4

You could use the bracket notation as property accessor.

globalClient[functionName]()
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use the [ ] operator for accessing the properties.

var globalClient = {
  funcA: function(){
    console.log('funcA is called');
  }
}

var functionName = 'func'.concat('A');
globalClient[functionName]();
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112