js 回调函数理解与应用

  定义:在JavaScript中,回调函数具体的定义为:函数A作为参数(函数引用)传递到另一个函数B中,并且这个函数B执行函数A。我们就说函数A叫做回调函数。如果没有名称(函数表达式),就叫做匿名回调函数。

  理解:回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

  举个例子:

//首先,创建通用诗的生成函数;它将作为下面的getUserInput函数的回调函数
 
    function genericPoemMaker(name, gender) {
        console.log(name + " is finer than fine wine.");
        console.log("Altruistic and noble for the modern time.");
        console.log("Always admirably adorned with the latest style.");
        console.log("A " + gender + " of unfortunate tragedies who still manages a perpetual smile");
    }
 
        //callback,参数的最后一项,将会是我们在上面定义的genericPoemMaker函数
        function getUserInput(firstName, lastName, gender, callback) {
            var fullName = firstName + " " + lastName;
 
            // Make sure the callback is a function
            if (typeof callback === "function") {
            // Execute the callback function and pass the parameters to it
            callback(fullName, gender);
            }
        }    
getUserInput("Michael", "Fassbender", "Man", genericPoemMaker);
 
 // 输出 /* Michael Fassbender is finer than fine wine. Altruistic and noble for the modern time. Always admirably adorned with the latest style. A Man of unfortunate tragedies who still manages a perpetual smile. */ 

我们可以换一个回调函数试试:

function greetUser(customerName, sex) { var salutation = sex && sex === "Man" ? "Mr." : "Ms."; console.log("Hello, " + salutation + " " + customerName); } // 将greetUser作为一个回调函数 getUserInput("Bill", "Gates", "Man", greetUser); // 这里是输出 Hello, Mr. Bill Gates
原文地址:https://www.cnblogs.com/mengqi-S/p/7657945.html