2

Consider I have four functions:

function first() {
  console.log("This is the first function");
}

function second() {
  console.log("This is the second function");
}

function third() {
  console.log("This is the third function");
}

function fourth(name) {
  console.log("This is the fourth function " + name);
}

I am trying to pass the above list of functions to a function:

var list_of_functions = [first, second, third, fourth];
executeFunctions(list_of_functions);

This is the executeFunction:

function executeFunctions(list_of_functions) {
  console.log("inside new executeFunctions");
  list_of_functions.forEach(function(entry) {
    entry();
  });
}

How do I pass the name argument for my fourth function in the array itself ? Is there any way to do this ?

For example, I would like to do something like this:

var list_of_functions = [first, second, third, fourth("Mike")];

Obviously, the above statement is wrong. Is there any way to do this ?

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
Vinoth Kumar C M
  • 10,378
  • 28
  • 89
  • 130

2 Answers2

5

You could use the bind function:

var list_of_functions = [first, second, third, fourth.bind(this, "Mike")];

The first argument of bind is what you want this to be inside the fourth function (can be this, null, or any other object).

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
1

Wrap it with another function

var list_of_functions = [first, second, third, function(){return fourth('Mike');}];
sectus
  • 15,605
  • 5
  • 55
  • 97