什么是JavaScript中的回調函數?

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函數調用中的匿名函數參數也是回調! 因此,該示例的原始回調實際上是由另一個回調執行的。 如果可以幫助,請注意不要嵌套太多回調,因為這可能會導致“回調地獄”! 顧名思義,處理它并不是一件愉快的事情。

翻譯自: https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390964.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390964.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390964.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java 集合-集合介紹

2017-10-30 00:01:09 一、Java集合的類關系圖 二、集合類的概述 集合類出現的原因:面向對象語言對事物的體現都是以對象的形式,所以為了方便對多個對象的操作,Java就提供了集合類。數組和集合類同是容器,有什么不同:數…

為什么Java不允許super.super.method();

問題:為什么Java不允許super.super.method(); 我想出了這個問題,認為這個是很好解決的(也不是沒有它就不行的)如果可以像下面那樣寫的話: Override public String toString() {return super.super.toString(); }我不…

Exchange 2016部署實施案例篇-04.Ex基礎配置篇(下)

上二篇我們對全新部署完成的Exchange Server做了基礎的一些配置,今天繼續基礎配置這個話題。 DAG配置 先決條件 首先在配置DGA之前我們需要確保DAG成員服務器上磁盤的盤符都是一樣的,大小建議最好也相同。 其次我們需要確保有一塊網卡用于數據復制使用&…

數據庫課程設計結論_結論:

數據庫課程設計結論In this article, we will learn about different types[Z Test and t Test] of commonly used Hypothesis Testing.在本文中,我們將學習常用假設檢驗的不同類型[ Z檢驗和t檢驗 ]。 假設是什么? (What is Hypothesis?) This is a St…

JavaScript數據類型:Typeof解釋

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well.typeof是一個JavaScript關鍵字,當您調用它時將…

asp.net讀取用戶控件,自定義加載用戶控件

1、自定義加載用戶控件 ceshi.aspx頁面 <html><body> <div id"divControls" runat"server"></div> </body></html> ceshi.aspx.cs頁面 System.Web.UI.UserControl newUC (System.Web.UI.UserControl)Page.LoadContro…

配置Java_Home,臨時環境變量信息

一、內容回顧 上一篇博客《Java運行環境的搭建---Windows系統》 我們說到了配置path環境變量的目的在于控制臺可以在任意路徑下都可以找到java的開發工具。 二、配置其他環境變量 1. 原因 為了獲取更大的用戶群體&#xff0c;所以使用java語言開發系統需要兼容不同版本的jdk&a…

網頁縮放與窗口縮放_功能縮放—不同的Scikit-Learn縮放器的效果:深入研究

網頁縮放與窗口縮放內部AI (Inside AI) In supervised machine learning, we calculate the value of the output variable by supplying input variable values to an algorithm. Machine learning algorithm relates the input and output variable with a mathematical func…

在構造器里調用可重寫的方法有什么問題?

問題&#xff1a;在構造器里調用可重寫的方法有什么問題&#xff1f; 我有一個檢票頁面的類通過抽象方法的結果去去設置頁的標題 public abstract class BasicPage extends WebPage {public BasicPage() {add(new Label("title", getTitle()));}protected abstract…

創建hugo博客_如何創建您的第一個Hugo博客:實用指南

創建hugo博客Hugo is a great tool to use if you want to start a blog.如果您想創建博客&#xff0c;Hugo是一個很好的工具。 I use Hugo myself for my blog, flaviocopes.com, and Ive been using it for more than two years. I have a few reasons for loving Hugo.我本…

Python自動化開發01

一、 變量變量命名規則變量名只能是字母、數字或下劃線的任意組合變量名的第一個字符不能是數字以下關鍵字不能聲明為變量名 [and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not,…

記錄關于vs2008 和vs2015 的報錯問題

出現了 VS2008無法創建項目&#xff0c;無法打開項目的情況&#xff0c;提示這個注冊表鍵值有問題 HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ MSBuild \ ToolsVersions \ 14.0&#xff0c; 但是查看了注冊表沒有這個鍵。費盡辛萬苦&#xff0c;中午在思密達的一個網站上看到…

未越獄設備提取數據_從三星設備中提取健康數據

未越獄設備提取數據Health data is collected every time you have your phone in your pocket. Apple or Android, the phones are equipped with a pedometer that counts your steps. Hence, health data is recorded. This data could be your one free data mart for a si…

怎么樣用System.out.println在控制臺打印出顏色

問題&#xff1a;怎么樣用System.out.println在控制臺打印出顏色 怎么樣才能在控制臺里打印顏色啊&#xff1f;我想要展示一些有顏色的字體&#xff0c;當處理器發送數據和接收數據的時候&#xff0c;也使用不同顏色的字體。 回答一 在這個Java類里面帶有public static 的數…

sql注入語句示例大全_SQL Order By語句:示例語法

sql注入語句示例大全Order By is a SQL command that lets you sort the resulting output from a SQL query.Order By是一個SQL命令&#xff0c;可讓您對SQL查詢的結果輸出進行排序。 訂購依據(ASC&#xff0c;DESC) (Order By (ASC, DESC)) ORDER BY gives us a way to SORT…

[BZOJ2599][IOI2011]Race 點分治

2599: [IOI2011]Race Time Limit: 70 Sec Memory Limit: 128 MBSubmit: 3934 Solved: 1163[Submit][Status][Discuss]Description 給一棵樹,每條邊有權.求一條簡單路徑,權值和等于K,且邊的數量最小.N < 200000, K < 1000000 Input 第一行 兩個整數 n, k第二..n行 每行三…

分詞消除歧義_角色標題消除歧義

分詞消除歧義折磨數據&#xff0c;它將承認任何事情 (Torture the data, and it will confess to anything) Disambiguation as defined in the vocabulary.com dictionary refers to the removal of ambiguity by making something clear and narrowing down its meaning. Whi…

北航教授李波:說AI會有低潮就是胡扯,這是人類長期的追求

這一輪所謂人工智能的高潮&#xff0c;和以往的幾次都有所不同&#xff0c;那是因為其受到了產業界的極大關注和參與。而以前并不是這樣。 當今世界是一個高度信息化的世界&#xff0c;甚至我們有一只腳已經踏入了智能化時代。而在我們日常交流和信息互動中&#xff0c;迅速發…

創建字符串枚舉的最好方法

問題&#xff1a;創建字符串枚舉的最好方法 用一個枚舉類型去表示一組字符串的最好方法是什么 我嘗試這樣&#xff1a; enum Strings{STRING_ONE("ONE"), STRING_TWO("TWO") }我怎么樣才可以像使用字符串那樣使用它們&#xff1f; 回答一 我不知道你想…

網絡安全習慣_健康習慣,確保良好的網絡安全

網絡安全習慣In a similar fashion to everyone getting the flu now and again, the risk of catching a cyberattack is a common one. Both a sophisticated social engineering attack or grammatically-lacking email phishing scam can cause real damage. No one who c…