考虑我有四个功能:
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")];
显然,上述说法是错误的。有没有办法做到这一点?
答案 0 :(得分:5)
您可以使用bind
功能:
var list_of_functions = [first, second, third, fourth.bind(this, "Mike")];
bind
的第一个参数是您希望this
位于fourth
函数内(可以是this
,null
或任何其他对象)。
答案 1 :(得分:1)
用另一个功能
包裹它var list_of_functions = [first, second, third, function(){return fourth('Mike');}];