Home>Article>Web Front-end> Detailed analysis of callback functions in JavaScript
This article brings you relevant knowledge aboutJavaScript, 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]
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. Itis passed to other codes as a parameter, and its function is tofacilitate callingthis (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.
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:
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 .
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: Analysis: this points to the caller of the function/method that isclosest 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; 4. Why is the callback function used? There is a very important reason -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 thearrow 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.
JavaScript is an event-driven language. This means thatJavaScript will not stop the current operation because it is waiting for a response, but will listen to other Continue executionwhen the event occurs. Let’s look at a basic example:
Analysis: As you expected, thefirstfunction is executed first, and then
secondis Execution - Console output: 1 2
functionfirstcontains 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 usesetTimeout, 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:
The running result of the entire program is: 2 1, not the original 1 2.Even if we call thefirst()
function first, the output result we record is insecond( )
after the function.
This is not a problem of JavaScript not executing functions in the order we want, butJavaScript not waiting before continuing to executesecond()
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.
Definition:The callbackfunction is considered ahigh-level function, one that is passed as a parameterHigh-level function for another function. Theessence of the callback function is a pattern(a pattern for solving common problems), so the callback function is also called thecallback 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!