The problem of callback function

  1. function tes(a){
        var c=1;
        a(c)
    }
    function yui(n){
        console.log(n)
    }
    tes(yui)

ask the gods that the results of the first method and the second callback function are the same. Is there any difference between the first method and the second callback function? Please explain.

Sep.27,2021

function tes(){
    var c=1;
    yui(c)   //c
}
function yui(n){
    console.log(n)  // n = c = 1; 1
}
tes()  //tes


function tes(a){  // ` yui(n){console.log(n)}`
    var c=1;
    a(c)  //a(c) = a(1) = yui(1)
}
function yui(n){  //yui
    console.log(n)
}
tes(yui)  //tes yui

the second way is more like the functional programming we advocate now, passing functions as parameters, as you said, the results are all the same.


as mentioned above, the second type belongs to the advocated functional programming on the one hand
in this case, compared with the first, the difference or advantage lies in the following three points:
1. Two functions can be used as independent functions without relying on external variables or conditions. In the first kind, tes must rely on yui
2 and functions as parameters to break through the long-standing limits of thinking. Bring more flexibility
3, because the function is independent, it is easier to "semantic". For example, in this case, tes can be changed to handleC,yui to log-> handleC (log)-> to print out C. (it's a little far-fetched here, but it can be understood in this direction.)

Menu