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
  • 45,213
  • 22
  • 199
  • 169
EGN
  • 2,480
  • 4
  • 26
  • 39
  • 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
  • 129,518
  • 31
  • 228
  • 259
1

You can access properties of object by []:

obj['Func2']();
madox2
  • 49,493
  • 17
  • 99
  • 99
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
  • 45,213
  • 22
  • 199
  • 169