A preliminary study of JavaScript function (iv)---callback function

Source: Internet
Author: User


callback function


Since the function is the same as any data that is assigned to a variable, she can, of course, be defined, deleted, copied, and passed as arguments to other functions, as is the case with other data.



We define a function that has two parameters for the function type, and then performs the functions executed by the two parameters separately.


 
function her(){ return a() + b();
}
function one(){ return 1;
}
fucntion two(){ return 2;
}
her(one, two) // 3


In fact, we can also use anonymous functions directly (i.e. function expressions) instead of one (), or one (), as the parameters of the target function:


Her (function {return1}, function {return2}); 3


When we pass function A to function B and B to execute a, A is a callback (callback function), and if this is a or an anonymous function, we call it an anonymous callback function.



Benefits of the callback function:



1. She can allow us to pass parameters without naming (meaning that the use of variable names can be saved);



2. We can delegate a function call operation to another function (which means that some code writing work can be reduced);



3. Also helps improve performance;



Here's a simple example:


function main(callback)   {      
      alert("I am main function");   
      alert("Invoke callback function..");   
      callback();   
}   
function b(){   
     alert("I am callback function: b");   
}   
 function c(){   
      alert("I am callback function: c");   
}   
           
 function test() {   
      main(b);   
      main(c);   
} 




In Javascrip, a function is a built-in class object, which means that it is a type of object that can be used for the management of built-in objects just like other objects of the string, Array, number, and object classes.  Because the function is actually an object, it can be "stored in a variable, passed to (another) function by argument, created inside a function, and returns the result value from the function." Because function is a built-in object, we can pass it as an argument to another function, defer execution to the function, or even return it after execution. This is the essence of using a callback function in JavaScript. The remainder of this article will fully learn the JavaScript callback function. The callback function may be the most widely used functional programming technique in JavaScript, and perhaps just a small piece of JavaScript or jquery code will leave a mystery to the developer, and reading this article may help you eliminate the mystery. callback functionFrom a well-known programming paradigm- function-type programming, at the basic level, functional programming specifies the parameters of the function.  Functional programming Although the current scope of use has become smaller, but it has been "professional smart" programmers as a kind of difficult to understand technology, previously, and the future will be so. Fortunately, functional programming has been elaborated by the General people like you and me can also understand and use. One of the main techniques of functional programming is the callback function, which you will soon read that implementing a callback function is as simple as passing a generic parameter variable. This technology is so simple that I wonder why it is often included in the high-level topic of JavaScript.What is a callback or advanced function?


A callback function is considered an advanced function, an advanced function that is passed as a parameter to another function (called "otherfunction"), and the callback function is called (or executed) within the otherfunction. The essence of a callback function is a pattern (a pattern that solves common problems), so a callback function is also called a callback pattern.



Consider the following callback functions that are commonly used in jquery:


$("#btn_1").click(function() {
  alert("Btn 1 Clicked");
});


As seen in the previous example, we pass a function to the parameter of the click Method, and the click Method invokes (or executes) the callback function we pass to it. This example gives a typical way to use the callback function in JavaScript and is widely used in jquery.



Savor a typical example of another basic javascript:


var friends = ["Mike", "Stacy", "Andy", "Rick"];
friends.forEach(function (eachName, index){
    console.log(index + ". " + eachName); 
}); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick


Once again, we passed an anonymous function in the same way (a function without a function name) to the Foreach method as a foreach parameter.



So far, we have passed an anonymous function as a parameter to another function or method. Before looking at other more complex callback functions, let's take a look at how callbacks work and implement a callback function of our own.


How is the callback function implemented?


We can use a function like a variable, as an argument to another function, in another function as the return result, and call it in another function. When we pass a callback function as a parameter to another function, we pass only the definition of the function and do not execute it in the argument.



When the containing (called) function has a callback function defined in the parameter, it can be called at any time (that is, callback).



This means that the callback function is not executed immediately, but rather "callback" it (as its name) in the specified position within the function body containing the function. So, even if the first example of jquery looks like this:


$("#btn_1").click(function() {
  alert("Btn 1 Clicked");
});


The anonymous function is called in the function body of the Click function, even if there is no name, it can be accessed by the containing function through the arguments object.



The callback function is a closed packet.
When you pass a callback function as a parameter to another function, the callback function is executed somewhere within the body of the containing function function, as if the callback function is defined in the body of the function that contains the function. This means that the callback function is closed and you want to learn more about closures in the next chapter!



It is known that the closure function can access the scope of the containing function, so the callback function can access the variable that contains the function, even the global variable.


Basic principles of implementing callback functions


Simply put, there are a few principles to follow when implementing a callback function yourself.



Use a named function or an anonymous function as a callback



In the preceding jquery and foreach examples, we define anonymous functions in the parameters that contain the function, which is one of the common forms of using the callback function, and the other is often used in the form of defining a function with a name and passing the function name as an argument to another function, for example:


 
function logStuff (userData) { if ( typeof userData === "string")
    {
        console.log(userData);
    } else if ( typeof userData === "object")
    { for (var item in userData) {
            console.log(item + ": " + userData[item]);
        }
    }
}
function getInput (options, callback) {
    allUserData.push (options);
    callback (options);
}
getInput ({name:"Rich", speciality:"JavaScript"}, logStuff);





Passing parameters to the callback function
Because the callback function is executed just like a normal function, we can pass parameters to it. You can pass a callback function as a parameter to any property that contains a function (or a global property). In the previous example, we passed the options containing the function as arguments to the callback function. The following example lets us pass a global variable or local variable to the callback function:


 
var generalLastName = "Clinton";
function getInput (options, callback) {
    allUserData.push (options);
    callback (generalLastName, options);
}





Make sure the callback is a function before executing
Before calling, it is often advisable to ensure that callbacks passed in through parameters are a required function. In addition, making the callback function optional is also a good practice.



Let's refactor the GetInput function in the example above to make sure that the callback function is properly checked.


 
function getInput(options, callback) {
    allUserData.push(options); if (typeof callback === "function") {
        callback(options);
    }
}





If the GetInput function is not properly checked (checking whether callback is a function or passed in by argument), our code will cause a run-time error.



Problems with the callback function that contains this object
When the callback function is a method containing the This object, we must modify the method that executes the callback function to protect the contents of this object. Otherwise the This object will point to the Global Window object (if the callback function is passed to the global function), or to the containing function. Let's take a look at the following code


 
var clientData = {
    id: 094545,
    fullName: "Not Set",
    setUserName: function (firstName, lastName)  { this.fullName = firstName + " " + lastName;
    }
}

function getUserInput(firstName, lastName, callback)  {
    callback (firstName, lastName);
}





In the following example code, when Clientdata.setusername is executed, This.fullname does not set the property fullname in the Clientdata object, but instead sets the FullName in the Window object. Because Getuserinput is a global function. This behavior occurs because the this object points to the Window object in the global function.


getUserInput ("Barack", "Obama", clientData.setUserName);
console.log (clientData.fullName);
console.log (window.fullName);





Protect this object with the call or Apply function



We can solve the problem in the previous example by using the call or Apply function. So far, we know that every function in JavaScript has two methods: Call and apply. These methods can be used to set the contents of this object inside a function and to pass the content to the object that the function argument points to.



Call takes the value of used as the This object inside the function as the first parameter, and the remaining Arguments to is passed to the function is passed individually (separated by commas of course). The Apply function ' s first parameter is also the value of be used as the thisobject inside the function and the last PA  Rameter is a array of values (or the arguments object) to pass to the function. (The paragraph is too awkward to translate, let the original experience)



This sounds complicated, but let's look at how easy it is to use apply and call. To solve the problem in the previous example, we use the Apply function as follows:


 
function getUserInput(firstName, lastName, callback, callbackObj)  {
    callbackObj
    callback.apply (callbackObj, [firstName, lastName]);
}


By using the Apply function to set the This object correctly, we can now execute the callback function correctly and set the FullName property in the Clientdata object correctly.


Getuserinput ("Barack", "Obama", Clientdata.setusername, Clientdata);


We can also use the call function, but in this case we use the Apply function.



Multiple callback functions are also allowed
We can pass multiple callback functions to another function, just like passing multiple variables. This is a typical example of an AJAX function using jquery:


 
function successCallback() { // Do stuff before send }

function successCallback() { // Do stuff if success message received }

function completeCallback() { // Do stuff upon completion }

function errorCallback() { // Do stuff if error received }

$.ajax({
    url:"http://fiddle.jshell.net/favicon.png",
    success:successCallback,
    complete:completeCallback,
    error:errorCallback

});














A preliminary study of JavaScript function (iv)---callback function


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.