Javascript中回调数组的不同参数

时间:2015-10-30 07:29:55

标签: javascript arrays function

考虑我有四个功能:

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);
}

我试图将上面的函数列表传递给函数:

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

这是executeFunction

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

如何在数组本身中传递fourth函数的name参数?有没有办法做到这一点?

例如,我想做这样的事情:

var list_of_functions = [first, second, third, fourth("Mike")];
显然,上述说法是错误的。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:5)

您可以使用bind功能:

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

bind的第一个参数是您希望this位于fourth函数内(可以是thisnull或任何其他对象)。

答案 1 :(得分:1)

用另一个功能

包裹它
var list_of_functions = [first, second, third, function(){return fourth('Mike');}];