首页 > 技术文章 > 回调函数

qionglouyuyu 2015-06-29 14:38 原文

回调函数的定义为:传递一个函数A到另一个函数B中,由B调用A,我们就说函数A叫做回调函数。如果没有名称,就叫做匿名回调函数。

例1:Javascript中的回调函数
function invoke_and_add(a,b){
  return a()+b();
}
function one(){
  return 1;
}
function two(){
  return 2;
}
invoke_and_add(one ,two);
例2:Javascript中的匿名回调函数
invoke_and_add(function(){return 1;},function(){return 2;})  

 

适用于:
1. 通过一个统一接口实现不同的内容 
回调函数的使用在C++中相当于函数指针
int TVPrice(int price) 
{
    printf("The price of the TV is %d. \n", price);
    return 0;  
} 
int PCPrice(int price) 
{ 
    printf("The price of the PC is %d. \n", price);
    return 0;
} 
void Caller(int n, int (*ptr)())//指向函数的指针作函数参数,第一个参数是为指向函数的指针服务的, 
{                               //不能写成void Caller(int (*ptr)(int n))
    (*ptr)(n);  
} 
int main() 
{ 
    Caller(3000, TVPrice); 
    Caller(5000, PCPrice);
    return 0; 
}
 
2. 异步调用
A先告诉B去点亮,然后自己点亮。B的点亮操作并不会阻塞A。
function lightUp(A, callback){ 

 callback(); 

 A.lightUp(); 

} 

function callback(){

 B.lightUp(); 

}
***同步调用时这样的***
var temp = false; 

while(!temp){
  temp = wait(A.lightUp());
}

B.lightUp();

 

推荐阅读