Detailed analysis of callback functions in JavaScript
This article brings you relevant knowledge about JavaScript, which mainly introduces the relevant content of the callback function, including what is the callback function, what are the characteristics of the callback function, and this in the callback function Point to the problem, let’s take a look at it, I hope it will be helpful to everyone.
[Related recommendations: JavaScript video tutorial, web front-end]
1. What is a callback function (callback)?
Pass the function as a parameter to another function. When you need to use this function, callback and run() this function.
The callback function is an executable code segment. It is passed to other codes as a parameter , and its function is to facilitate calling this (callback function) code when needed. (Passed as a parameter to another function, the function as a parameter is the callback function)
Understanding: A function can be passed as a parameter to another function.
<script> function add(num1, num2, callback) { var sum = num1 + num2; callback(sum); } function print(num) { console.log(num); } add(1, 2, print); //3 </script>
Analysis: In add(1, 2, print);, the function print is passed into the add function as a parameter, but it does not work immediately, but var sum = num1 num2; after running This function is called only when sum needs to be printed. (This is passed as a parameter to another function, and the function as a parameter is the callback function.
Anonymous callback function:
<script> function add(num1, num2, callback) { var sum = num1 + num2; callback(sum); } add(1, 2, function (sum) { console.log(sum); //=>3 }); </script>
2. What are the characteristics of the callback function?
1. It will not be executed immediately
When the callback function is passed as a parameter to a function, only the definition of the function is passed and will not be executed immediately. Just like an ordinary function, The callback function must also be called through the ()
operator in the number of calling functions before it will be executed .
2. The callback function is a closure
Callback A function is a closure, which means it can access its outer-defined variables.
3. Type judgment before execution
It is best to confirm that it is a function before executing the callback function .
<script> function add(num1, num2, callback) { var sum = num1 + num2; //判定callback接收到的数据是一个函数 if (typeof callback === 'function') { //callback是一个函数,才能当回调函数使用 callback(sum); } } </script>
3. The pointing problem of this in the callback function
Note that when the callback function is called, the execution context of this is not the context when the callback function is defined, but when it is called The context in which the function is located.
Example:<script> function createData(callback){ callback(); } var obj ={ data:100, tool:function(){ createData(function(n){ console.log(this,1111); //window 1111 }) } } obj.tool(); </script>
closest to it or at the nesting level , the function closest to it here is
function(n), which will return to the callback() above. At this time, the caller is not obj but window. Solve the callback function this Pointing method 1: Arrow functionCallback function (Analysis: After the callback function is written with an arrow function, this pointing is very clear, which is the closest to it or the nesting level The caller of function/method, so here is obj. Method 2 to solve the callback function this points to: var self = this;If the callback function is a normal function) When the parameters are passed into another function, if you don’t know how to call it internally Callback function, there will be a problem that this in the callback function points unclearly (for example, in the above example, this points not to obj but to window). So use the arrow function as the callback function, and then pass in another parameter as a parameter There will be no problem of unclear this pointing in the function.
<script> function createData(callback){ callback(); } var obj ={ data:100, tool:function(){ createData((n)=>{ this.data = n; }) } } obj.tool(); console.log(obj.data); </script>Copy after login
<script> function createData(callback){ callback(999); } var obj ={ data:100, tool:function(){ var self = this; //这里的this指向obj,然后当一个变量取用 createData(function(n){ self.data = n; }) } } obj.tool(); console.log(obj.data); </script>
JavaScript is an event-driven language. This means that JavaScript will not stop the current operation because it is waiting for a response, but will listen to other Continue execution when the event occurs. Let’s look at a basic example:
<script> function first() { console.log(1); } function second() { console.log(2); } first(); second(); </script>
first function is executed first, and then
second is Execution - Console output: 1 2
function first contains some code
that cannot be executed immediately? For example an API request where we have to send a request and then wait for a response? To simulate this situation, we will use setTimeout, which is a JavaScript function that calls a function after a period of time. We delay the function for 500 milliseconds to simulate an API request. The new code looks like this:
<script> function first() { // 模拟代码延迟 setTimeout(function () { //所以function(){console.log(1)}是回调函数 console.log(1); }, 500); } function second() { console.log(2); } first(); second(); </script>
The running result of the entire program is: 2 1, not the original 1 2. Even if we call the first()
function first, the output result we record is in second( )
after the function.
This is not a problem of JavaScript not executing functions in the order we want, but JavaScript not waiting before continuing to execute second()
first()
responds to 's question. Callback is the way to ensure that one piece of code is executed before another piece of code is executed.
5. What is the relationship between callback functions and asynchronous operations? Is the callback function asynchronous?
Definition: The callback function is considered a high-level function, one that is passed as a parameter High-level function for another function. The essence of the callback function is a pattern (a pattern for solving common problems), so the callback function is also called the callback pattern.
In short: a function is called within another function. And can be passed as parameters to other functions.
So: There is no relationship between callback functions and asynchronous operations! ! !
Then why do many asynchronous operations have backfill functions? ?
Q: Is the asynchronous operation that you know about the function of callbacks? ? ? Not really.
Callback: It can be understood more as a kind of business logic. Asynchronous programming: the execution sequence of JS code.
Simple understanding: callback, as the name suggests, means calling back.
eg1: You ordered takeout, but the food you wanted to eat happened to be gone, so you left your phone number with the store owner. After a few days, the store had it, and the store clerk called your number. Then you got the call and ran to the store to buy it. In this example, your phone number is called the callback function. When you leave your phone number to the store clerk, it is called the registration callback function. When the store has goods later, it is called the event associated with the callback. When the store clerk calls you, it is called the callback function. When you go to the store to pick up the goods, it is called responding to the callback event.
eg2: For another example, you send an axios request. After the request is successful, the success callback function is triggered, and the request failure triggers the failure callback function. The callback function here is more like a tool. The background uses this tool to tell you whether you succeeded or failed. All asynchronous operations here have nothing to do with callbacks. The real asynchronous operation is the then method.
[Related recommendations: JavaScript video tutorial, web front-end]
The above is the detailed content of Detailed analysis of callback functions in JavaScript. 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

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

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.

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

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
