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
47.4k23 gold badges205 silver badges173 bronze badges
asked Mar 10, 2016 at 21:14
EGN
2,6024 gold badges29 silver badges41 bronze badges
-
2See property accessorselclanrs– elclanrs2016年03月10日 21:15:00 +00:00Commented Mar 10, 2016 at 21:15
-
Possible duplicate of Accessing a JSON property (String) using a variableMike Cluck– Mike Cluck2016年03月10日 21:16:05 +00:00Commented Mar 10, 2016 at 21:16
-
@elclanrs: Thanks, exactly what I was looking forEGN– EGN2016年03月10日 21:18:33 +00:00Commented Mar 10, 2016 at 21:18
3 Answers 3
Just look up the object's property using [], then use () to call the function
obj[functionToCall]();
answered Mar 10, 2016 at 21:18
Mulan
136k35 gold badges240 silver badges276 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can access properties of object by []:
obj['Func2']();
answered Mar 10, 2016 at 21:15
madox2
52.3k21 gold badges106 silver badges101 bronze badges
Comments
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)
answered Mar 11, 2016 at 17:41
John Slegers
47.4k23 gold badges205 silver badges173 bronze badges
Comments
lang-js