回调函数(callback function)

计算机编程中,”回调“是可执行代码的参考,或者是一段可执行程序,”回调“被当做参数传入另外的代码中。这种”回调“机制允许软件底层代码调用上层定义的函数。

很多人对”回调“感到困惑是因为这个”回调“这个名字在作怪。

一个回调方法可以作为参数传入另外一个方法中,回调方法的执行是某些事件所激发的。参数的”调回“本质是,一旦父方法执行完,作为参数的回调方法(回调函数)就会被调用。也就是说父方法调回执行作为参数传过来的方法。

//An innocuous looking method which will become known as a callback method
//because of the way in which we will invoke it.
function meaningOfLife() {
    log("The meaning of life is: 42");
}


//An innocuous looking method which just takes an int and prints it to screen, and takes a function reference to be executed when printANumber completes
function printANumber(int number, function callbackFunction()) {
    print("The number you provided is: " + number);
}

function event() {
   printANumber(6, meaningOfLife());
}

The number you provided is: 6
The meaning of life is: 42


之所以叫回调函数,是因为在那些含有指针概念的编程语言中有这样的叫法。如果你的编程语言没有指针概念,那么就可以不去关心回调函数的执行细节。仅仅把它理解成一个函数作为参数被另外一个函数调用就成了。因此,无论父函数什么时候被调用(不论什么情况:按钮点击,定时器到时),当父函数执行完后,回调函数就会被调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值