详解什么是回调函数(小白也能看得懂的,示例讲解)

A nice way of imagining how a callback function works is that it is a function that is "called at the back" of the function it is passed into.

Maybe a better name would be a "call after" function.

This construct is very useful for asynchronous behaviour where we want an activity to take place whenever a previous event completes.

A callback function is a function which is:

  • accessible by another function, and
  • is invoked after the first function if that first function completes

按照 MDN 的描述:回调函数是作为参数传给另一个函数的函数,然后通过在外部函数内部调用该回调函数以完成某种操作

让我用人话解释一下,回调函数是一个函数,将会在另一个函数完成执行后立即执行。回调函数是一个作为参数传给另一个 JavaScript 函数的函数。这个回调函数会在传给的函数内部执行。

在 JavaScript 中函数被看作是一类对象。对于一类对象,我们的意思是指数字、函数或变量可以与语言中的其他实体相同。作为一类对象,可以将函数作为变量传给其他函数,也可以从其他函数中返回这些函数。

例如:

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('请输入你的名字。');
  callback(name);
}

processUserInput(greeting);

以上范例为 同步 回调,它是立即执行的。

然而需要注意的是,回调函数经常被用于继续执行一个异步 完成后的操作,它们被称为异步回调。

另一个例子:

// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
function printANumber(number, callbackFunction) {
    console.log("The number you provided is: " + number);
    setTimeout(function() { callbackFunction(); }, 3000); 
    console.log("second");
}
 
// a function which we will use in a driver function as a callback function
function printFinishMessage() {
    console.log("I have finished printing numbers.");
}
 
// Driver method

printANumber(6, printFinishMessage);

执行printANumber函数后,结果:

> "The number you provided is: 6"
> "second"
> "I have finished printing numbers."

The order of the output here is important. Since callback functions are called afterwards, "I have finished printing numbers" is printed last, not first.

Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when the parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback function is then invoked.

Some languages support constructs where multiple callback function arguments are supported, and are called based on how the parent function completes (i.e. one callback is called in the event that the parent function completes successfully, another is called in the event that the parent function throws a specific error, etc).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值