var array_of_functions = [
    first_function('a string'),
    second_function('a string'),
    third_function('a string'),
    forth_function('a string')
]

array_of_functions[0];

That does not work as intended because each function in the array is executed when the array is created.

What is the proper way of executing any function in the array by doing:

array_of_functions[0];  // or, array_of_functions[1] etc.

Thanks!

share|improve this question
1  
Does 'a string' need to be known at the time the array is populated, or can the caller of the function pass it in? – Crescent Fresh Feb 5 '11 at 17:33
I'd love to get more detail on what you're trying to accomplish, because there might be a better way of handling this. – jlbruno Feb 5 '11 at 17:36
1  
"Array of Functions" - or as we like to call it an object with methods – symcbean Feb 5 '11 at 17:38

4 Answers

up vote 19 down vote accepted
var array_of_functions = [
    first_function,
    second_function,
    third_function,
    forth_function
]

and then when you want to execute a given function in the array:

array_of_functions[0]('a string');
share|improve this answer
Thank you, all, for the amazingly quick, helpful responses. I should have thought of this solution sooner ("duh" moment). Coding while feeling tired can be counter-productive :-P – Nick Feb 5 '11 at 17:50

Or just:

var myFuncs = {
  firstFun: function(string) {
    // do something
  },

  secondFunc: function(string) {
    // do something
  },

  thirdFunc: function(string) {
    // do something
  }
}
share|improve this answer

I think this is what the original poster meant to accomplish:

var array_of_functions = [
    function() { first_function('a string') },
    function() { second_function('a string') },
    function() { third_function('a string') },
    function() { forth_function('a string') }
]

for (i = 0; i < array_of_functions.length; i++) {
    array_of_functions[i]();
}

Hopefully this will help others (like me 20 minutes ago :-) looking for any hint about how to call JS functions in an array.

share|improve this answer

Without more detail of what you are trying to accomplish, we are kinda guessing. But you might be able to get away with using object notation to do something like this...

var myFuncs = {
  var firstFun = function(string) {
    // do something
  },

  var secondFunc = function(string) {
    // do something
  },

  var thirdFunc = function(string) {
    // do something
  }
}

and to call one of them...

myFuncs.firstFunc('a string')
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.