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
47.4k23 gold badges205 silver badges173 bronze badges
asked Mar 10, 2016 at 21:14
3

3 Answers 3

3

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

obj[functionToCall]();
answered Mar 10, 2016 at 21:18
Sign up to request clarification or add additional context in comments.

Comments

1

You can access properties of object by []:

obj['Func2']();
answered Mar 10, 2016 at 21:15

Comments

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)

answered Mar 11, 2016 at 17:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.