Home  >  Article  >  Web Front-end  >  In-depth analysis of callback functions in js (detailed explanation sharing)

In-depth analysis of callback functions in js (detailed explanation sharing)

奋力向前
奋力向前forward
2021-09-17 10:53:092183browse

In the previous article " An article explaining the this pointing problem in js (with code) ", I introduced you to the this pointing problem in js. The following article will give you a detailed explanation of the callback function in js. Friends, take a look.

In-depth analysis of callback functions in js (detailed explanation sharing)

Detailed explanation of JS callback function

JS callback function

What is a callback function, official explanation : When the program is running, under normal circumstances, the application program will often call pre-prepared functions in the library through the API. However, some library functions require the application to pass it a function first, so that it can be called at the appropriate time to complete the target task. The function that is passed in and called later is called the callback function.

Usually pass a function B into another function A, and call function A when needed.

To put it bluntly, callback is backtracking. First define the function body to be used, and then call this function after use. We usually pass callback as a parameter into the one defined first. function. Let's first look at a piece of jquery code:

$("p").hide(1000,function(){
alert("The paragraph is now hidden");
});

The above jquery is a callback function. First, after executing the hide effect, it then calls the function Callback.

Let’s look at a piece of JS code again to see how the callback function is implemented:

function Buy(name,goods1,callback) {
    alert(name+' buy '+goods1);
    if(callback&&typeof(callback)==="function")
        callback();
}
Buy('xiaoming','apple',function(){
    alert("shopping finish");
});

A very simple code. I don’t know what I want to buy at the beginning. When I buy something, I immediately put the previous When the defined function is called, it is best to add judgment rules, because the premise is that callback must be a function, and the output result is:

xiaoming buy apple
shopping finish

Closure and callback

Let’s look at a closure question. Click on the first and fourth nodes respectively. The execution result is:

var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
    nodes[i].addEventListener(&#39;click&#39;, function() {
        console.log(&#39;You clicked element #&#39; + i);
   });
}

Although the main test here is closure, addEventListener is a closure, and the anonymous function is a callback function, i is the variable in the closure. When the callback of addEventListener is executed, the loop has ended. At this time, the variable i is assigned the value node.length, and node.length is the total number of nodes. So the result is

You clicked element # node.length

How to change it, change its return value to a function, since the value of the i variable will be released, then we will introduce i, so that the value of each loop Just save them all in memory:

var nodes = document.getElementsByTagName(&#39;button&#39;);
for (var i = 0; i < nodes.length; i++) {
(function(i) {
    nodes[i].addEventListener(&#39;click&#39;, function () {
        console.log(&#39;You clicked element #&#39; + i);
        })
       })(i);
}

PHP callback function

Let’s briefly talk about how to implement the callback function in PHP (the result is 1, 2, 3, 4):

<?php
    $array=array(1,2,3,4);
    array_walk($array,function($value){
        echo $value;});
?>

php performs callback processing for each incoming array element. Let’s take a look at PHP’s closure. Use the use keyword to inherit variables outside the scope:

<?php
    function getcouter(){
        $i=0
        return function() use($i)(
            echo $i;
        )};
    }
    $counter=getcounter();
    echo $counter();
    echo $counter();
?>

The return result is:

1,1

Official PHP usage method

class hello {
function callback($a,$b) {
echo "$a,$b";
}
static function callback($c,$d){
echo "$c,$d";        
}
}
//将类名作为参数
call_user_func(array(&#39;hello&#39;,&#39;callback&#39;),"hello","world");
//输出 hello,world
//将对象作为参数
call_user_func(array(new hello(),&#39;callback&#39;),"hello","world");
//将静态方法作为参数
call_user_func(hello::callback,"hello","world");
//输出 hello,world

In fact, in principle, JS and PHP are similar. They both define the function first and then call it when needed. .

Recommended learning: JS video tutorial

The above is the detailed content of In-depth analysis of callback functions in js (detailed explanation sharing). For more information, please follow other related articles on the PHP Chinese website!

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