


Detailed explanation of callback functions in JavaScript and how to use it
In JavaScript, functions are first-class objects, which means that functions can be used like objects with first-class management. Since functions are actually objects: they can be "stored" in variables, passed as function parameters, created within functions, and returned from functions.
Because functions are first-class objects, we can use callback functions in JavaScript. In the following article, we will learn all about callback functions. Callback functions are probably the most used functional programming technique in JavaScript. Although they literally look like a small piece of JavaScript or jQuery code, they are still a mystery to many developers. After reading this article you can understand how to use callback functions.
The callback function is a concept derived from a programming paradigm called functional programming. Simply put, functional programming is about using functions as variables. Functional programming was - and still is - not widely used - it used to be seen as a secret technique reserved for specially trained, master-level programmers.
Fortunately, the technique of function programming has now been fully explained so that ordinary people like me and you can use it easily. One of the main tricks in functional programming is callback functions. In the following content, you will find that implementing a callback function is actually as simple as passing parameters to a normal function. This tip is so simple that I often wonder why it's often included in chapters on advanced JavaScript techniques.
What is a callback or higher-order function
A callback function, also known as a higher-order function, is a function that is passed as a parameter to A function of another function (here we call the other function otherFunction
), the callback function is called in otherFunction
. A callback function is essentially a programming pattern (a solution created for a common problem), so using callback functions is also called the callback pattern.
Here is a simple and common example of using callback functions in jQuery:
1 2 3 4 5 |
|
As you can see in the previous example, we passed a function as a parameter to click
method. The click
method will call (or execute) the function we pass to it. This is a typical use of callback functions in JavaScript, and it is widely used in jQuery.
Here is another example of a typical callback function in JavaScript:
1 2 3 4 5 |
|
Once again, notice that we are passing an anonymous function (a function without a name) as a parameter to forEach
method.
So far, we have passed anonymous functions as arguments to another function or method. Before we look at more practical examples and write our own callback functions, let's understand how callback functions work.
How does the callback function work?
Because functions are first-class objects in JavaScript, we treat functions like objects, so we can pass functions like variables, return functions in functions, and return functions in other functions function used in. When we pass a callback function as a parameter to another function, we only pass the function definition. We are not executing the function on the parameters. We don't pass the function with a pair of execution parentheses ()
like we normally do with execution functions.
It is important to note that the callback function will not be executed immediately. It is "called back" (as its name suggests) at a specific point in time within the containing function. So even though the first jQuery example looks like this:
1 2 3 4 5 |
|
This anonymous function will be called later inside the function body. Even if there is a name, it is still obtained through the arguments
object within the containing function.
The callback function is a closure
When you can pass a callback function as a variable to another function, the callback function contains it is executed at a certain point within the function as if the callback function was defined within the containing function. This means that the callback function is essentially a closure.
As we know, a closure can enter the scope of the function that contains it, so the callback function can obtain variables in the function that contains it, as well as variables in the global scope.
Basic principles of implementing callback functions
The callback function is not complicated, but before we start creating and using the callback function, we should be familiar with it Several basic principles for implementing callback functions.
Use named or anonymous functions as callbacks
In the previous jQuery example and forEach example, we used the parameter defined in the parameter position Anonymous function as callback function. This is a common magic trick in the use of callback functions. Another common pattern is to define a named function and pass the function name as a variable to the function. For example, the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
传递参数给回调函数
既然回调函数在执行时仅仅是一个普通函数,我们就能给它传递参数。我们能够传递任何包含它的函数的属性(或者全局属性)作为回调函数的参数。在前面的例子中,我们将options作为一个参数传递给了回调函数。现在我们传递一个全局变量和一个本地变量:
1 2 3 4 5 6 7 8 |
|
在执行之前确保回调函数是一个函数
在调用之前检查作为参数被传递的回调函数确实是一个函数,这样的做法是明智的。同时,这也是一个实现条件回调函数的最佳时间。
我们来重构上面例子中的getInput
函数来确保检查是恰当的。
1 2 3 4 5 6 7 8 9 |
|
如果没有适当的检查,如果getInput
的参数中没有一个回调函数或者传递的回调函数事实上并不是一个函数,我们的代码将会导致运行错误。
使用this对象的方法作为回调函数时的问题
当回调函数是一个this
对象的方法时,我们必须改变执行回调函数的方法来保证this
对象的上下文。否则如果回调函数被传递给一个全局函数,this
对象要么指向全局window
对象(在浏览器中)。要么指向包含方法的对象。
我们在下面的代码中说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
在下面你的代码例子中,当clientData.setUsername
被执行时,this.fullName
并没有设置clientData
对象中的fullName
属性。相反,它将设置window
对象中的fullName
属性,因为getUserInput
是一个全局函数。这是因为全局函数中的this
对象指向window
对象。
1 2 3 4 |
|
使用Call和Apply函数来保存this
我们可以使用Call
或者Apply
函数来修复上面你的问题。到目前为止,我们知道了每个JavaScript中的函数都有两个方法:Call
和 Apply
。这些方法被用来设置函数内部的this对象以及给此函数传递变量。
call
接收的第一个参数为被用来在函数内部当做this
的对象,传递给函数的参数被挨个传递(当然使用逗号分开)。Apply
函数的第一个参数也是在函数内部作为this
的对象,然而最后一个参数确是传递给函数的值的数组。
听起来很复杂,那么我们来看看使用Apply
和Call
有多么的简单。为了修复前面例子的问题,我将在下面你的例子中使用Apply
函数:
1 2 3 4 5 |
|
使用Apply
函数正确设置了this
对象,我们现在正确的执行了callback
并在clientData
对象中正确设置了fullName
属性:
1 2 3 4 5 |
|
我们也可以使用Call
函数,但是在这个例子中我们使用Apply
函数。
允许多重回调函数
我们可以将不止一个的回调函数作为参数传递给一个函数,就像我们能够传递不止一个变量一样。这里有一个关于jQuery中AJAX的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
“回调地狱”问题以及解决方案
在执行异步代码时,无论以什么顺序简单的执行代码,经常情况会变成许多层级的回调函数堆积以致代码变成下面的情形。这些杂乱无章的代码叫做回调地狱因为回调太多而使看懂代码变得非常困难。我从node-mongodb-native,一个适用于Node.js的MongoDB驱动中拿来了一个例子。这段位于下方的代码将会充分说明回调地狱:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
你应该不想在你的代码中遇到这样的问题,当你当你遇到了
你将会时不时的遇到这种情况
这里有关于这个问题的两种解决方案。
给你的函数命名并传递它们的名字作为回调函数,而不是主函数的参数中定义匿名函数。
模块化L将你的代码分隔到模块中,这样你就可以到处一块代码来完成特定的工作。然后你可以在你的巨型应用中导入模块。
创建你自己的回调函数
既然你已经完全理解了关于JavaScript中回调函数的一切(我认为你已经理解了,如果没有那么快速的重读以便),你看到了使用回调函数是如此的简单而强大,你应该查看你的代码看看有没有能使用回调函数的地方。回调函数将在以下几个方面帮助你:
避免重复代码(DRY-不要重复你自己)
在你拥有更多多功能函数的地方实现更好的抽象(依然能保持所有功能)
让代码具有更好的可维护性
使代码更容易阅读
编写更多特定功能的函数
创建你的回调函数非常简单。在下面的例子中,我将创建一个函数完成以下工作:读取用户信息,用数据创建一首通用的诗,并且欢迎用户。这本来是个非常复杂的函数因为它包含很多if/else
语句并且,它将在调用那些用户数据需要的功能方面有诸多限制和不兼容性。
相反,我用回调函数实现了添加功能,这样一来获取用户信息的主函数便可以通过简单的将用户全名和性别作为参数传递给回调函数并执行来完成任何任务。
简单来讲,getUserInput
函数是多功能的:它能执行具有无种功能的回调函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
调用getUserInput
函数并将genericPoemMaker
函数作为回调函数:
1 2 3 4 5 6 7 |
|
因为getUserInput
函数仅仅只负责提取数据,我们可以把任意回调函数传递给它。例如,我们可以传递一个greetUser
函数:
1 2 3 4 5 6 7 8 9 10 |
|
我们调用了完全相同的getUserInput
函数,但是这次完成了一个完全不同的任务。
正如你所见,回调函数很神奇。即使前面的例子相对简单,想象一下能节省多少工作量,你的代码将会变得更加的抽象,这一切只需要你开始使用毁掉函数。大胆的去使用吧。
在JavaScript编程中回调函数经常以几种方式被使用,尤其是在现代Web应用开发以及库和框架中:
异步调用(例如读取文件,进行HTTP请求,等等)
时间监听器/处理器
setTimeout
和setInterval
方法一般情况:精简代码
结束语
JavaScript回调函数非常美妙且功能强大,它们为你的Web应用和代码提供了诸多好处。你应该在有需求时使用它;或者为了代码的抽象性,可维护性以及可读性而使用回调函数来重构你的代码。
推荐教程:《JavaScript视频教程》
The above is the detailed content of Detailed explanation of callback functions in JavaScript and how to use it. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

The writing methods of java callback function are: 1. Interface callback, define an interface, which contains a callback method, use the interface as a parameter where the callback needs to be triggered, and call the callback method at the appropriate time; 2. Anonymous inner class callback , you can use anonymous inner classes to implement callback functions to avoid creating additional implementation classes; 3. Lambda expression callbacks. In Java 8 and above, you can use Lambda expressions to simplify the writing of callback functions.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Introduction to the basic writing and usage of Java callback functions: In Java programming, the callback function is a common programming pattern. Through the callback function, a method can be passed as a parameter to another method, thereby achieving indirect call of the method. The use of callback functions is very common in scenarios such as event-driven, asynchronous programming and interface implementation. This article will introduce the basic writing and usage of Java callback functions, and provide specific code examples. 1. Definition of callback function A callback function is a special function that can be used as a parameter
