JavaScript callback function, closure scope, call,apply function to solve the scope problem of this

Source: Internet
Author: User
Tags types of functions

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. The callback function comes from a well-known programming paradigm-functional programming, at the basic level, where functional programming specifies the parameters of a 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://note. The item in the click Method's parameter is a function, not a variable.//the item is a Callback function$ ("#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 isA typical way of using callback function in JavaScript is given, and it 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 + 1 + "." + 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 parameter to foreach. 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 jquery example looks like this://the anonymous function is not being executed there in the parameter. The item is a callback function$ ("#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 closed 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, as if the callback function is defined in the function body that contains the function. This means that the callback function is closed, and if you want to learn more about closures, refer to the author's other post understand JavaScript Closures with Ease. It is known that the closure function can access the scope of the containing function, so the callback function can access the variable containing the function,Even a global variable. The basic principle of implementing a callback function is simply that you need to follow a few principles when implementing your callback function. Using a named function or an anonymous function as a callback in the preceding jquery and foreach example, we define an anonymous function in the parameter containing 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 pass the function name as an argument to another function, for example:?//Global Variablevar alluserdata = [];//generic logstuff function that prints to consolefunction l    Ogstuff (UserData) {if (typeof userData = = = "string") {Console.log (userData);  } else if (typeof userData = = = = "Object") {for (var item in userData) {Console.log (item + ":" +        Userdata[item]);    }}}//a function that takes and parameters, the last one A callback functionfunction getinput (options, callback) {    Alluserdata.push (options); callback (options);} When we call the GetInput function, we pass Logstuff as a parameter.//so Logstuff would be is the function that would calle D back (or executed) inside the GetInput functiongetinput ({name: "Rich", Speciality: "JavaScript"}, Logstuff);//Name:ric h//Speciality:javascript Pass parameters to the callback function because the callback function is executed just like a normal function, we can pass parameters to it. Any of the containing functions can beThe property (or global property) is passed as a parameter to the callback function. 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://global variablevar generallastname = "Clinton"; function getinput (options, callback) {All  Userdata.push (options);//Pass The global variable generallastname to the callback function callback (Generallastname, options);} It is often advisable to ensure that callbacks are passed in through parameters before the callback is a function before execution is called. 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);  Make sure the callback is a function if (typeof callback = = = "function") {//call it, since we have confirmed it    Is callable callback (options); If the GetInput function does not check properly (check if callback is a function or if it is passed through a parameter), our code will result in a run-time error. Problem with a 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://Define An object with some properties and a method//we'll later pass the method as a callback function to Another Functionvar clientdata = {ID: 094545, FullName: "Not Set",//Setusername was a method on the Clientdata object Setusername:function (Firstna Me, LastName) {//This refers to the FullName property in this object this.fullname = FirstName + "" + Last    Name; }}function getuserinput (FirstName, LastName, callback) {//Do other stuff to validate firstname/lastname here//N ow Save the names 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);//Not set//the FullName property is initialized on the window Objectconsole.log (window.fullname); Barack Obama uses the call or apply function to protect the This object 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 (separ Ated 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. This sounds complicated, but let's look at how easy it is to use apply and call, which is too clumsy to translate. To solve the problem in the previous example, we use the Apply function as follows://note that we had added an extra parameter for the callback object, called "Callbackobj" func tion Getuserinput (FirstName, LastName, Callback, Callbackobj) {//do-other stuff-Validate name here/ of the Apply function below would set the This object to be Callbackobj callback.apply (callbackobj, [FirstName, Lastnam E]);} 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. We Pass the Clientdata.setusername method and the Clientdata object as parameters. The Clientdata object is used by the Apply function to set the THis object?getuserinput ("Barack", "Obama", Clientdata.setusername, clientdata);//The FullName property on the Clientdat A was correctly setconsole.log (clientdata.fullname); Barack Obama 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 Ajax functions 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, Complet E:completecallback, error:errorcallback}); " Callback Hell "problem and Solution Async code execution is a simple way to execute in any order, and sometimes it is quite common that there are many levels of callback functions, and you look like the following code. The messy code below is called "Callback hell" because it's a cumbersome code that contains a lot of callbacks. I saw this example in Node-mongodb-native, MongoDB drives node. js. The sample code is like this: var p_client = new Db (' integration_tests_20 ', New Server (" 127.0.0.1 ", 27017, {}), {' PK ': custompkfactory});p _client.open (function (err, p_client) {p_client.drOpdatabase (function (err, done) {p_client.createcollection (' Test_custom_key ', function (err, collection) { Collection.insert ({' A ': 1}, Function (err, docs) {collection.find ({' _id ': New ObjectID ("Aaaaaaaaaaaa")}, Fu  Nction (err, cursor) {Cursor.toarray (err, items) {test.assertequals (1,                        Items.length);                    Let ' s close the DB P_client.close ();                });            });        });    }); });}); You are unlikely to encounter this problem in your own code, but if you run into it (or stumble into it later), there are two ways to solve the problem. Name and define your function, and pass the function name as a callback instead of defining an anonymous function in the parameter list of the main function. Modularity: Divide your code into modules so that you can spare a chunk of code to do special work. Then you can introduce this model into your large application. Implement your own callback function now you fully understand (I believe you have understood that if you do not read it quickly again) JavaScript uses the features of the callback and see that the callback is used so simple but powerful. You should see if your code has the opportunity to use the callback function, and you can consider using callbacks if you have the following requirements: Avoid duplicate code (dry-do not Repeat yourself) to better implement abstractions where you need more common functionality (can handle various types of functions). Enhanced code maintainability Enhanced code readability There are more customization features to implement your own callback function is very simple, in the following example, I can create a function to complete the work: Get user data, use user data to generate a common poem, using user data to welcome users, but this functionwill be a messy function, with if/else judgment everywhere, and there are even a lot of restrictions that cannot be performed on other functions that the application may need to process user data. Instead, I let the implementation add a callback function, so that the main function gets the user data and can pass the user's full name and gender to the parameters of the callback function and execute the callback function to accomplish any task. In short, the Getuserinput function is generic and can perform multiple callback functions with various functions. First, setup the generic poem Creator function; It would be is the callback function in the Getuserinput function below.function genericpoemmaker (name, gender) {CONSOLE.L    OG (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");} The callback, which is the last item in the parameter, would be our genericpoemmaker function we defined above.function g    Etuserinput (FirstName, LastName, Gender, callback) {var fullName = FirstName + "" + lastName; Make sure the callback is a function if (typeof callback = = = "function") {//Execute the callback function and P The parameters to it callback (FullName, GENDEr); }} call the Getuserinput function and pass the Genericpoemmaker function as a callback: Getuserinput ("Michael", "Fassbender", "Man", genericpoemmaker);// output/* 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.*/because the Getuserinput function only handles input of user data, we can pass any callback function to it. For example, we can pass a greetuser function like this. function GreetUser (customerName, sex) {var salutation = sex && sex = = = "Man"?  "Mr.": "Ms."; Console.log ("Hello," + Salutation + "" + CustomerName);}  Pass the GreetUser function as a callback to Getuserinputgetuserinput ("Bill", "Gates", "Mans", GreetUser);//And this is The Outputhello, Mr Bill gates, as in the previous example, we called the same getuserinput function, but this time we performed a completely different task. As you can see, the callback function provides a wide range of functions. Although the example mentioned earlier is very simple, think about how much you can save and how to better abstract your code when you start using a callback function. Come on! When you get up in the morning, think about it before you go to bed at night, and think about it when you rest ...  In JavaScript, we often use callback functions to note the following points, especially the current development of Web applications, in third-party libraries and frameworks for asynchronous execution (such as read files, send HTTP requests) event listening and processing set time-out and the method of the interval is generalized: code concise

  

JavaScript callback function, closure scope, call,apply function to solve the scope problem of this

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.