Home  >  Article  >  Web Front-end  >  Detailed analysis of callback functions in JavaScript

Detailed analysis of callback functions in JavaScript

WBOY
WBOYforward
2022-11-23 16:42:302873browse

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.

Detailed analysis of callback functions in JavaScript

[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>
Analysis: this points to the caller of the function/method that is

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 function

Callback function (

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>
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;

    <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>
4. Why is the callback function used?

There is a very important reason -

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>
Analysis: As you expected, the

first function is executed first, and then second is Execution - Console output: 1 2

But what happens if the

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>
Analysis: Here the function(){console.log(1)} function is passed as a parameter to the setTimeout function, because setTimeout is an official function, which contains many complex business programs. Therefore, after the function function(){console.log(1)} is passed in, it may not run immediately. To setTimeout, you must run it to function(){console. The function parameter will only be run when log(1)}. Does that mean the entire program just waits for setTimeout to run? no! ! !

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete