2

I have an object that contains many functions

var obj = {
    'Func1': function() {},
    'Func2': function() {},
    'Func3': function() {},
    'Func4': function() {}
...
}
var functionToCall = 'Func2';

I want to dynamically call a function inside the object using a string value. Any idea how to achieve this in JavaScript?

John Slegers
  • 41,615
  • 22
  • 193
  • 161
EGN
  • 2,290
  • 4
  • 25
  • 37
  • 2
    See [property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) – elclanrs Mar 10 '16 at 21:15
  • Possible duplicate of [Accessing a JSON property (String) using a variable](http://stackoverflow.com/questions/19300236/accessing-a-json-property-string-using-a-variable) – Mike Cluck Mar 10 '16 at 21:16
  • @elclanrs: Thanks, exactly what I was looking for – EGN Mar 10 '16 at 21:18

3 Answers3

3

Just look up the object's property using [], then use () to call the function

obj[functionToCall]();
Mulan
  • 119,326
  • 28
  • 214
  • 246
1

You can access properties of object by []:

obj['Func2']();
madox2
  • 45,325
  • 15
  • 94
  • 95
0

This is all there's to it :

var obj = {
    'Func1': function() { alert('Func1') },
    'Func2': function() { alert('Func2') },
    'Func3': function() { alert('Func3') },
    'Func4': function() { alert('Func4') }
}

var functionToCall = 'Func2';
obj[functionToCall]();

(see also this Fiddle)

John Slegers
  • 41,615
  • 22
  • 193
  • 161