Javascript回调函数那点事

研究了下Javascript 的回调函数,  网上已经有N多相关资料了, 整理下自己的思路,记录下自己的理解。


什么是回调(callback)? 

  在wiki上的是这么写的:  In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at later time as in an asynchronous callback. In all cases, the intention is to specify a function or subroutine as an entity that is, depending on the language, more or less similar to a variable


顾名思义,callback的最大特征也就是”don't call me, I will call you“, 在知乎上,各位大神有精彩的回答。


在这里,我想说的是两个细节的地方, 这个定义中的描述澄清了我对这两点的理解。

1. callback中的代码作为argument 传递对应到Javascript 代码中,也就是传递时function 不要带括号

下面是栗子。

我在用setTimeout 写了如下实例:

setTimeout(test(), 5000);
function test() {
  console.log("this is test");
}

你觉得会如何执行?

当时我很困惑的是为什么没有延迟5秒执行,反而每次都立即打印出"this is test"了。


从wiki中callback的定义可以看出来, 这是因为传递给setTimeOut的callback 不是argument, 而是带(), 也就是说函数被具体执行了。

把代码改为如下就可以了:

setTimeout(test, 5000);
function test() {
  console.log("this is test");
}


test 函数被延迟5秒执行。



2. callback 既可以是同步回调也可以异步回调

在JS中, 回调函数被广泛的用来解决异步问题,所以一看到回调,就容易想到异步。 其实回调函数只是用于解决异步的方式之一。

(有篇文章详细解读了解决Javascript 异步的4种方法 http://sporto.github.io/blog/2012/12/09/callbacks-listeners-promises/)


上面的setTimeout 是异步回调函数。

在wiki中有个回调函数的栗子, 略微做了些更改,这个就不是异步了。

function someAction(x, y, someCallback) {
    return someCallback(x, y);
}

function calcProduct(x, y) {
    return x * y;
}

function calcSum(x, y) {
    return x + y;
}
// alerts 75, the product of 5 and 15
console.log("the calcProduct result is " + (someAction(5, 15, calcProduct)));
// alerts 20, the sum of 5 and 15
console.log("the calcSum result is " + someAction(5, 15, calcSum));

在此,通过传入不同的函数可以处理处理不同场景,得到不同的结果。


回调函数有广泛的应用,一边学习一边应用一边总结中。。



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值