JavaScript closures Simple Comprehension

Source: Internet
Author: User


When it comes to closures, it must have been heard, and my simple understanding follows.
To tell the truth, there are not many scenes of actual manual closures in the work, but the third-party frameworks and components used in the project are more or less used in closures.
Therefore, it is very necessary to understand closures. Oh ...


One, what is closures
In short, it is the function that can read the variables inside other functions.
due to the nature of the JS variable scope, external variables cannot be accessed externally, and external variables can be used internally.


second, the use of the scene
1. Implement a private member.
2. Protect namespaces and avoid polluting global variables.
3. Cache variables.
4. Code Reuse

let's look at an example of encapsulation:

    1. var person = function () {
    2. Variable scope is inside function, external unreachable
    3. var name = "Default";
    4. return {
    5. Getname:function () {
    6. return name;
    7. },
    8. Setname:function (newName) {
    9. name = NewName;
    10. }
    11. }
    12. }();
    13. Console.log (Person.name); Direct access, the result is: undefined
    14. Console.log (Person.getname ()); The result is: Default
    15. Console.log (Person.getname ()); The result is: LANGJT
Copy Code



Then look at common closures in loops to solve the problem of referencing external variables:

    1. var aLi = document.getelementsbytagname (' li ');
    2. For (var i=0, len=ali.length; i<len; i++) {
    3. Ali[i].onclick = function () {
    4. alert (i); Regardless of which <li> element is clicked, the pop-up value is Len, indicating that I is the same as the value for printing I after for.
    5. };
    6. }
Copy Code



After using closures:

    1. var aLi = document.getelementsbytagname (' li ');
    2. For (var i=0, len=ali.length; i<len; i++) {
    3. Ali[i].onclick = (function (i) {
    4. return function () {
    5. alert (i); When you click on the <li> element, the corresponding subscript will pop up.
    6. }
    7. }) (i);
    8. }
Copy Code



Third, the matters needing attention
1. Memory leaks
Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page.
Like what:

    1. function foo () {
    2. var odiv = document.getElementById (' J_div ');
    3. var id = odiv.id;
    4. Odiv.onclick = function () {
    5. alert (odiv.id); There is a circular reference here, and the Odiv is still in memory after the low version of IE page closes. So try to cache the base type instead of the object.
    6. alert (ID);
    7. };
    8. Odiv = null;
    9. }
Copy Code



2. Variable naming
If the variables of the intrinsic function and the variable name of the external function are the same, then the intrinsic function cannot point to the variable with the same name as the outer function.
Like what:

    1. function foo (num) {
    2. return function (num) {
    3. Console.log (num);
    4. }
    5. }
    6. var f = new Foo (9);
    7. f (); Undefined
Copy Code



In fact, the above usage, the jargon called function currying, is to transform a function that accepts multiple parameters into a function that takes a single parameter (the first parameter of the initial function) and returns a new function that accepts the remaining parameters and returns the result. In essence, the features that can be cached by closures are also used, such as:

    1. var adder = function (num) {
    2. return function (y) {
    3. return num+y;
    4. };
    5. };
    6. var inc = Adder (1);
    7. var dec = adder (-1);
    8. Inc, Dec is now two new functions that will pass in parameter values (+/‐) 1
    9. Alert (inc (99));//100
    10. Alert (Dec (101));//100
    11. Alert (Adder (100) (2));//102
    12. Alert (Adder (2) (100));//102
Copy Code



Again such as Ali Yuber's Seajs Source:

    1. /**
    2. * Util-lang.js-the Minimal language enhancement
    3. */
    4. function Istype (type) {
    5. return function (obj) {
    6. return {}.tostring.call (obj) = = "[Object" + Type + "]"
    7. }
    8. }
    9. var IsObject = Istype ("Object");
    10. var isstring = Istype ("String");
Copy Code

JavaScript closures Simple Comprehension

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.