JavaScript Basic callback function

Source: Internet
Author: User

As mentioned earlier, a function object can be passed as a parameter to another function, when the function as a parameter is executed internally, then it is a callback function (Callback):

function Writecode (callback) {    //do something    ... Callback ();    // ...} function Introducebugs () {    //... make bugs}writecode (introducebugs);

In the above code, Introducebugs is called as a parameter to the Writecode, which is invoked during the execution of the Writecode function. So Introducebugs is a callback (CallBack) function.
A more practical callback function is given below. Suppose we have a findnodes function that can find all the nodes that satisfy a certain condition in a large array through a complex logic, and return these nodes:

var findnodes = function () {    var i = 100000,//big, heavy loop        nodes = [],//stores the result        found;//th E next node found    while (i) {        I-= 1;        Complex logic        here ... Nodes.push (found);    }    return nodes;};

In general, we all want functions to function single, so this function is only responsible for finding and returning the nodes that satisfy a certain piece. We then write another function, hide, which hides a given set of nodes, which takes an array of nodes as arguments and hides the nodes in the array one by one. Combining these two functions, we can complete a combination of functions, that is, find some nodes and hide them:

var hide = function (nodes) {    var i = 0, max = nodes.length;    for (; i < max; i + = 1) {        Nodes[i].style.display = "None";    }};/ /Executing the Functionshide (Findnodes ());

It looks good. However, the implementation of this method is not efficient. Both of these functions require a very long loop, and in fact, if every node that satisfies the condition is found, it is immediately hidden, so that it is more efficient: it only needs to loop 1 times. In order to practice this idea, but still the two tasks are implemented in different functions, we use the callback method to do:

refactored Findnodes () to accept a callbackvar findnodes = function (callback) {    var i = 100000,        nodes = [],
   found;    Check if callback is callable    if (typeof callback!== "function") {        callback = false;    }    while (i) {        I-= 1;        Complex logic        here ... Now callback:        if (callback) {            callback (found);        }        Nodes.push (found);    }    return nodes;};

Findnodes then returns all the nodes that satisfy the condition, but it also accepts a callback function that performs some task for each node that satisfies the condition. This task is given to the callback function to declare. Here is the specific callback function hide:

A callback Functionvar hide = function (node) {    Node.style.display = "None";};/ /Find the nodes and hide them as you gofindnodes (hide);

Of course, if hide only serves findnodes, sometimes we don't need to give it a name and declare it as an anonymous callback function:

Passing an anonymous callbackfindnodes (function (node) {    Node.style.display = "Block";});

This in the callback function
When this is used in a callback function, for example, this callback function is actually a method of the object MyApp paint:

var MyApp = {};myapp.color = "green"; myapp.paint = function (node) {    node.style.color = this.color;};

At this point we have a global function findenodes () to accept a callback function:

var findnodes = function (callback) {    //...    if (typeof callback = = = "function") {        callback (found);    }    // ...};

If you execute Findnodes (myapp.paint), you cannot achieve the expected results. Because the this pointer in Myapp.paint points to a property in an object when it is declared, that is, the object itself, but when Myapp.paint is executed as a callback function in the global function findnodes, the this pointer becomes global when it is pointed to during execution. This is (if in the browser, the Dom object).
The workaround is to pass the object that the callback function belongs to Findnodes, and then specify the object to which it belongs when executing the callback function:

Findnodes (Myapp.paint, MyApp);

So findnodes changed to this:

var findnodes = function (callback, callback_obj) {    //...    if (typeof callback = = = "function") {        callback.call (callback_obj, found);    }   // ...};

This looks a bit verbose, because the name of the object appears in the parameter list two times. We can also pass the name of this callback function as a string:

Findnodes ("Paint", MyApp);

Here Findnodes the corresponding changes to:

var findnodes = function (callback, callback_obj) {    if (typeof callback = = = "string") {        callback = Callback_obj[ca Llback];    }    //...    if (typeof callback = = = "function") {        callback.call (callback_obj, found);    }   // ...};

JavaScript Basic callback function

Related Article

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.