zoukankan      html  css  js  c++  java
  • 回调函数

    回调函数的定义为:传递一个函数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. 
    ", price);
        return 0;  
    } 
    int PCPrice(int price) 
    { 
        printf("The price of the PC is %d. 
    ", 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();
  • 相关阅读:
    python函数名和左括号之间不能有空格
    linux版本选择
    filter_map
    awk统计总结
    Spring Boot + Redis 实现各种操作
    手机号正则校验
    判断windows系统
    Redis分布式锁
    shell 脚本快速部署 SpringBoot 项目
    Java主流的Http请求--原生的HttpURLConnection
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4607439.html
Copyright © 2011-2022 走看看