jquery - 写一个允许回调的函数?

Mat*_*hew 0 javascript jquery

可能重复:
Javascript回调编程?

很多jquery函数允许回调.大多数语法如下:

$('.selector').slideUp('fast', function(){
    alert('slideUp has completed');
});
Run Code Online (Sandbox Code Playgroud)

如果我正在编写自己的函数,我怎样才能确保它在调用之前完成(即提供回调参数)

mač*_*ček 5

var foo = function(bar, callback){
  console.log(bar);
  if(typeof callback == "function"){
    callback();
  }
};

foo("hello world", function(){
  console.log("done!");
});
Run Code Online (Sandbox Code Playgroud)

产量

hello world
done!
Run Code Online (Sandbox Code Playgroud)

或者,您可以像这样调用回调

callback.call(this, arg1, arg2);
Run Code Online (Sandbox Code Playgroud)

这会将foo函数(和可选参数)的范围传递给回调函数.

var foo = function(bar, callback){
  console.log(bar);
  if(typeof callback == "function"){
    callback.call(this, bar);
  }
};

foo("hello world", function(x){
  console.log(x + " is done!");
});
Run Code Online (Sandbox Code Playgroud)

产量

hello world
hello world is done!
Run Code Online (Sandbox Code Playgroud)