JavaScript closures Detailed

Source: Internet
Author: User
Tags closure

First, what is anonymous function

Create a function and assign it to the variable functionname, in which case the function created is the anonymous function. (function expression is an anonymous function)

Second, closed package

1. What is a closure?

Closures are functions that can read other functions ' internal variables.

Only sub-functions inside the function can read local variables, so the closure can be simply understood as " a function defined inside a function ".

We just have to take F2 as the return value, we can not read its internal variables outside the F1!

function F1 () {    var num = 1;     function F2 () {        console.log (num)    }    return  F2;}  var result = F1 (); Console.log (Result ());  //1

2, the use of closures

Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times.

function F1 () {    var num = 1;     function F2 () {        Console.log (+num)    }    return  F2;}  var result = F1 (); Console.log (Result ());   //2console.log (Result ()); // 3

The reason is that F1 is the parent function of F2, and the scope of F2 is bound to the active and global variable objects of the F1 function (the whole family object is destroyed only when the Web page is closed), which causes F2 to always be in memory, and F2 's presence depends on F1, Therefore, F1 is always in memory and will not be reclaimed by the garbage collection mechanism after the call ends.

3. note points for using closures

1) 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, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function.

2) The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function.

 var name = "the window";  var object ="My object"function() {  returnfunction
    () {                returnthis. Name;   };   }};alert (Object.getnamefunc ()  ); // the execution environment of the Window anonymous function is global, so its this object usually points to Window. 

4. Closure application Scenarios

1. Use closures instead of global variables

Global variable, test1 is the global variable var test1=111;function outer () {    console.log (test1);} Outer (); 111console.log (test1); 111//closures, Test2 is a local variable, which is the purpose of closures //We often use global variables in small scopes, which can be replaced by closures at this time. (function () {    var test2=222;    function test () {        console.log ("Test closure:" +test2);    }    Test (); Test closure: 222}); Console.log (test2);//Undefined, there is no access to test2

Again such as:
(function () {    var now = new Date ();    if (now.getmonth () = = 0 && now.getdate () = = 1) {        console.log ("Happy new year!")    }) ();

2. Accessing parameters inside a function outside the function or in other functions

function test () {    var num = 1;    function Other () {        console.log (++num)    }    return to other;}  var result = Test (); Console.log (Result ());  2console.log (Result ()); 3

3. using closures to mimic block-level scopes

(function () {    for (var i =0;i<5;i++) {        console.log (i)    }    Console.log (i);//5//itself only to 4, but this place is still accessible, All outputs 5}); Console.log (i); Undefined //using closures, a block-level scope is formed, allowing access to the outside. 

JavaScript closures Detailed

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.