博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
什么是JavaScript中的回调函数?
阅读量:2523 次
发布时间:2019-05-11

本文共 5463 字,大约阅读时间需要 18 分钟。

This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.

本文简要介绍了JavaScript编程语言中的回调函数的概念和用法。

函数就是对象 (Functions are Objects)

The first thing we need to know is that in Javascript, functions are first-class objects. As such, we can work with them in the same way we work with other objects, like assigning them to variables and passing them as arguments into other functions. This is important, because it’s the latter technique that allows us to extend functionality in our applications.

我们需要知道的第一件事是,在Javascript中,函数是一流的对象。 这样,我们可以像处理其他对象一样使用它们,例如将它们分配给变量并将它们作为参数传递给其他函数。 这很重要,因为后一种技术使我们能够扩展应用程序中的功能。

回调函数 (Callback Functions)

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed. It’s the combination of these two that allow us to extend our functionality.

回调函数是一个作为参数传递给另一个函数的函数,以后将被“回调”。 接受其他函数作为参数的函数被称为高阶函数 ,其包含所述回调函数被执行为逻辑。 两者的结合使我们能够扩展功能。

To illustrate callbacks, let’s start with a simple example:

为了说明回调,让我们从一个简单的示例开始:

function createQuote(quote, callback){   var myQuote = "Like I always say, " + quote;  callback(myQuote); // 2}function logQuote(quote){  console.log(quote);}createQuote("eat your vegetables!", logQuote); // 1// Result in console: // Like I always say, eat your vegetables!

In the above example, createQuote is the higher-order function, which accepts two arguments, the second one being the callback. The logQuote function is being used to pass in as our callback function. When we execute the createQuote function (1), notice that we are not appending parentheses to logQuote when we pass it in as an argument. This is because we do not want to execute our callback function right away, we simply want to pass the function definition along to the higher-order function so that it can be executed later.

在上面的示例中, createQuote是高阶函数,它接受两个参数,第二个参数是回调。 logQuote函数被用作我们的回调函数。 当我们执行createQuote函数(1)时 ,请注意,当我们将logQuote作为参数传递时,没有在logQuote 后面加上括号。 这是因为我们不想立即执行回调函数,我们只想将函数定义传递给高阶函数,以便以后可以执行。

Also, we need to ensure that if the callback function we pass in expects arguments, that we supply those arguments when executing the callback (2). In the above example, that would be the callback(myQuote); statement, since we know that logQuote expects a quote to be passed in.

另外,我们需要确保如果传入的回调函数期望参数,那么在执行回调(2)时我们将提供这些参数。 在上面的示例中,这将是callback(myQuote); 语句,因为我们知道logQuote希望传递一个报价。

Additionally, we can pass in anonymous functions as callbacks. The below call to createQuote would have the same result as the above example:

此外,我们可以将匿名函数作为回调传递。 以下对createQuote调用将具有与以上示例相同的结果:

createQuote("eat your vegetables!", function(quote){   console.log(quote); });

Incidentally, you don’t have to use the word “callback” as the name of your argument, Javascript just needs to know that it’s the correct argument name. Based on the above example, the below function will behave in exactly the same manner.

顺便说一句,你不必用“回拨”作为参数的名称,使用Javascript只需要知道它是正确的参数名称。 根据上面的示例,下面的函数将以完全相同的方式运行。

function createQuote(quote, functionToCall) {   var myQuote = "Like I always say, " + quote;  functionToCall(myQuote);}

为什么要使用回调功能? (Why use Callback functions?)

Most of the time we are creating programs and applications that operate in a synchronous manner. In other words, some of our operations are started only after the preceding ones have completed. Often when we request data from other sources, such as an external API, we don’t always know when our data will be served back. In these instances we want to wait for the response, but we don’t always want our entire application grinding to a halt while our data is being fetched. These situations are where callback functions come in handy.

大多数时候,我们正在创建以同步方式运行的程序和应用程序。 换句话说,我们的某些操作仅在上述操作完成后才开始。 通常,当我们从其他来源(例如外部API)请求数据时,我们并不总是知道何时将数据送回。 在这些情况下,我们希望等待响应,但是我们并不总是希望在获取数据时整个应用程序停止运行。 在这些情况下,回调函数非常有用。

Let’s take a look at an example that simulates a request to a server:

让我们看一个模拟对服务器请求的示例:

function serverRequest(query, callback){  setTimeout(function(){    var response = query + "full!";    callback(response);  },5000);}function getResults(results){  console.log("Response from the server: " + results);}serverRequest("The glass is half ", getResults);// Result in console after 5 second delay:// Response from the server: The glass is half full!

In the above example, we make a mock request to a server. After 5 seconds elapse the response is modified and then our callback function getResults gets executed. To see this in action, you can copy/paste the above code into your browser’s developer tool and execute it.

在上面的示例中,我们向服务器发出了模拟请求。 5秒钟后,将修改响应,然后执行我们的回调函数getResults 。 要查看实际效果,您可以将以上代码复制/粘贴到浏览器的开发人员工具中并执行。

Also, if you are already familiar with setTimeout, then you’ve been using callback functions all along. The anonymous function argument passed into the above example’s setTimeout function call is also a callback! So the example’s original callback is actually executed by another callback. Be careful not to nest too many callbacks if you can help it, as this can lead to something called “callback hell”! As the name implies, it isn’t a joy to deal with.

另外,如果您已经熟悉setTimeout ,那么您一直都在使用回调函数。 传递到上述示例的setTimeout函数调用中的匿名函数参数也是回调! 因此,该示例的原始回调实际上是由另一个回调执行的。 如果可以帮助,请注意不要嵌套太多回调,因为这可能会导致“回调地狱”! 顾名思义,处理它并不是一件愉快的事情。

翻译自:

转载地址:http://tqrwd.baihongyu.com/

你可能感兴趣的文章
[ffmpeg 扩展第三方库编译系列] 关于libvpx mingw32编译问题
查看>>
虚拟现实技术对人类是福还是祸?
查看>>
P3106 GPS的决斗
查看>>
hdoj1164
查看>>
简单工厂模式
查看>>
Using关键字的用法
查看>>
标准C程序设计七---60
查看>>
[Silverlight入门系列]使用MVVM模式(4):Prism的NotificationObject自动实现INotifyPropertyChanged接口...
查看>>
工作用工具
查看>>
字符串操作(字符数统计及字符串反转)
查看>>
TexturePacker license Key免费获取方式
查看>>
Android APK反编译
查看>>
两年面试你心得
查看>>
GBK编码相关
查看>>
hdu 1301 Jungle Roads (最小生成树)
查看>>
Java 多态 构造方法
查看>>
ActiveMQ-持久化存储方式
查看>>
个人简介
查看>>
树莓派xrdp无法连接
查看>>
python之路-day25-包
查看>>