Javascript closure usage Example Analysis _ javascript skills

Source: Internet
Author: User
This article mainly introduces the concept and usage of Javascript closures. It provides an in-depth analysis of the functions of closures and precautions for use in the form of examples, which is of great practical value, if you need it, you can refer to the examples in this article to analyze the concept and usage of Javascript closures. Share it with you for your reference. The details are as follows:

When talking about closures, I think everyone has heard of them. Let's talk about my simple understanding.
To be honest, there are not many scenarios for writing closures manually at work, but the third-party frameworks and components used in the project use closures more or less.
Therefore, it is necessary to understand closures. Haha...

1. What is a closure?

In short, it is a function that can read internal variables of other functions.
Because of the JS variable scope, internal variables cannot be accessed externally, and internal variables can be used internally.

II. Application scenarios

1. Implement private members.
2. Protect the namespace and avoid global variables contamination.
3. cache variables.

Let's look at an example of encapsulation:

The Code is as follows:

Var person = function (){
// The variable scope is inside the function and cannot be accessed from outside.
Var name = "default ";

Return {
GetName: function (){
Return name;
},
SetName: function (newName ){
Name = newName;
}
}
}();

Console. log (person. name); // direct access. The result is undefined.
Console. log (person. getName (); // The result is: default.
Console. log (person. setName ("langjt "));
Console. log (person. getName (); // The result is langjt.

Let's look at the common closures in the loop to solve the problem of referencing external variables:

The Code is as follows:

Var aLi = document. getElementsByTagName ('lil ');
For (var I = 0, len = aLi. length; I ALi [I]. onclick = function (){
Alert (I); // no matter which one you click

  • The pop-up values are all len, indicating that I is the same as printing I after.
    };
    }


    After the closure is used:

    The Code is as follows:

    Var aLi = document. getElementsByTagName ('lil ');
    For (var I = 0, len = aLi. length; I ALi [I]. onclick = (function (I ){
    Return function (){
    Alert (I); // click

  • The corresponding subscript is displayed.
    }
    }) (I );
    }

    Iii. Notes

    1. Memory leakage

    Because the closure will make the variables in the function be stored in the memory, the memory consumption is very large, so the closure cannot be abused, otherwise it will cause web page performance problems.
    For example:

    The Code is as follows:

    Function foo (){
    Var oDiv = document. getElementById ('J _ DIV ');
    Var id = oDiv. id;
    ODiv. onclick = function (){
    // Alert (oDiv. id); There is a circular reference here. After the IE lower version page is closed, the oDiv is still in the memory. Therefore, Cache basic types rather than objects as much as possible.
    Alert (id );
    };
    ODiv = null;
    }

    2. variable naming

    If the internal function variable and the external function variable name are the same, the internal function can no longer point to the variable with the same name as the external function.
    For example:

    The Code is as follows:

    Function foo (num ){
    Return function (num ){
    Console. log (num );
    }
    }
    Var f = new foo (9 );
    F (); // undefined

    In fact, in the above usage, the term "Currying" is to convert a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function, and return the technology of the new function that accepts the remaining parameters and returns results. Essentially, the closure can be cached, for example:

    The Code is as follows:

    Var adder = function (num ){
    Return function (y ){
    Return num + y;
    };
    };

    Var inc = adder (1 );
    Var dec = adder (-1 );
    // Inc, dec is now two new functions, the function is to pass in the parameter value (+/-) 1
    Alert (inc (99); // 100
    Alert (dec (101); // 100
    Alert (adder (100) (2); // 102
    Alert (adder (2) (100); // 102

    For example:

    The Code is as follows:

    /**
    * Util-lang.js-The minimal language enhancement
    */
    Function isType (type ){
    Return function (obj ){
    Return {}. toString. call (obj) = "[object" + type + "]"
    }
    }

    Var isObject = isType ("Object ");
    Var isString = isType ("String ");

    I hope this article will help you design javascript programs.

  • 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.