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?

3

3 Answers 3

3

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

obj[functionToCall]();
Sign up to request clarification or add additional context in comments.

Comments

1

You can access properties of object by []:

obj['Func2']();

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)

Comments

Your Answer

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.