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?

4
  • 1
    Use bracket notation globalClient["func" + "B"]() Commented Oct 24, 2016 at 7:01
  • 2
    This is a dup of many, many other answers. Commented Oct 24, 2016 at 7:02
  • 1
    take a look at this stackoverflow.com/questions/359788/…. I hope this is what you are looking for Commented Oct 24, 2016 at 7: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. Commented Oct 24, 2016 at 7:13

2 Answers 2

4

You could use the bracket notation as property accessor.

globalClient[functionName]()
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. Thanks for this.
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]();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.