如果要传递函数,只需按名称引用它而不带括号:
function foo(x) {
alert(x);
}
function bar(func) {
func("Hello World!");
}
//alerts "Hello World!"
bar(foo);
但有时您可能希望传递包含参数的函数,但在调用回调之前不要调用它。为此,在调用它时,只需将其包装在匿名函数中,如下所示:
function foo(x) {
alert(x);
}
function bar(func) {
func();
}
//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });
如果您愿意,还可以使用 apply 函数,并拥有第三个参数,该参数是参数数组,如下所示:
function eat(food1, food2) {
alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args) {
//do stuff
//...
//execute callback when finished
callback.apply(this, args);
}
//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]);