回调函数

来源:互联网 发布:猴岛游戏论坛 网站源码 编辑:程序博客网 时间:2024/06/05 04:22

回调函数

概述

  1. 在维基上,关于回调函数式这样描述的:
    In computer programming, a callback is any executable code that is passed as an argument to other code, which is expected to call back(execute) the argument at a given time. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.
    回调函数示意图
  2. 在百度百科上,关于回调函数的描述如下:
    回调函数就是通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用,用于对该事件或条件进行响应。
  3. jQuery官方文档给出的关于回调函数的解释如下:
    Unlike many other programming language, JavaScript enables you to freely pass functions around to be executed at a later time. A callback is a function that is passed as an argument to another function and is executed after its parent functionhas completed. Callbacks are special because they patinetly wait to execute until their parent finishes. MeanWhile, the browser can be executing other functions or doing all sorts of other work.

JavaScript的回调函数

回调本质是一种设计模式。在JavaScript中,回调函数为:函数A作为参数(函数引用)传递到另一个函数B中,并且由函数B执行函数A。就称函数A为回调函数。如果函数A为匿名函数,就叫匿名回调函数。
回调不一定用于异步,同步(阻塞)的场景下也经常用到回调。
1. 同步回调的例子

var f2 = function(){    // do f2}var f1 = function(callback){    // do something    callback();}f1(f2);

这就是一个简单的同步回调的例子,f2函数作为参数传递给f1,f1执行完something后,会调用f2函数.
2. 异步回调的例子
最常见的要数AJAX

$.ajax({  url: "test.html",  context: document.body}).done(function() {   $(this).addClass("done");}).fail(function() { alert("error");}).always(function() { alert("complete"); });

以上是对JavaScript的回调函数的简单分析。

Java的回调函数

在Java中,如何使用回调函数呢?不如先从一个例子入手,对回调函数有一个大体的认知。
Java中没有函数指针,也不能将函数作为参数传递给另一个函数。但是Java可以持有对象的引用。因此可以用接口实现回调函数。
Android中的view类的点击监听事件,大量使用回调函数。
如下,首先定义一个接口listener,在该接口中定义了一个点击响应的方法。

public interface Listener{    public void onClick();}

定义一个button,这个button持有listener接口对象

public class Button{    Listener listener;    public void setListener(Listener listener){        this.listener = listener;    }    public void click(){        listener.onClick();    }}

定义一个场景类,用以模拟点击事件发生过程

public class Client{    public static void main(String[] args){        Button button = new Button();        button.setListener(new Listener(){            @Override            public void onClick(){                System.out.println("button is clicked");            }        });        button.click();    }}

button持有的Listener接口对象,通过内部类的方式进行实例化,对应的实现方法onClick()并不是由Listener实例对象进行调用,而是由button对象再某一时刻调用button对象的click()方法进行调用。那么对于Listener对象来说,这个onClick()方法便是回调函数。

0 0
原创粉丝点击