您的位置:首页 > Web前端 > JavaScript

Javascript回调函数那点事

2015-10-10 10:07 471 查看

研究了下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));

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

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



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: