JS Basics-Closures

Source: Internet
Author: User

About the understanding and use of the closure in JS.

First, Introduction

A child function can use a local variable in the parent function , which is called a closure. Usually refers to a function that has access to a variable in another function scope . When created, it is common to create another function in one function to access the local variables of the function through another function.

function box () {  var user = ' Lee ';  return function () {//Returns the box () local variable return user through an anonymous function  ;}  ;} Alert (Box () ());
Here an anonymous function is used to access the user variable in the parent function, and the value of the variable is returned, so we can access the anonymous function externally by calling box () directly.

There seems to be no effect here, a little superfluous. So why use closures?

Of course, it also has its own advantages: through the closure of the variable to achieve the memory, to avoid the global variable implementation of the cumulative

second, the use of closures to achieve the accumulation

Traditional way: Declare a global variable to implement the summation

var age=100; Declaration of Global Variables function box () {age++;} Box (); alert (age);
In this way, if global variables can cause a lot of unimaginable trouble in large-scale software development, we should usually minimize the use of global variables. However, if you use a local variable declaration method, you cannot implement the additive.

Local variable mode:

function box () {var age=100;age++;return age;}  Alert (Box ());  The box method needs to be called multiple times, and each execution will reinitialize the age of 101 always.
so how to avoid the initialization of local variables each time, here is the closure to solve.

With closures, variables remain in memory for accumulation:

function box () {var age=100;   Local Variables in box return function () {//anonymous functions age++;        return age;}  } var b=box ();   Alert (b ());  This can be achieved by calling multiple box functions here, and keeping the value of the age variable in memory alert (b ());
This can be done in the form of closures above, but multiple functions need to be called, and we can use loops to improve this behavior.

three, the closure in the cycle

Applications of closures in the loop can use these methods to achieve the same effect

1. An anonymous function returns an array

function box () {var arr=[];for (var i=0;i<5;i++) {arr[i]=function () {  return i;}} return arr;  Returns an array of}for (i=0;i<5;i++)  //continuous implementation loop output {alert (box () [i] ());//result is 5 x 5}
Note : If you execute alert (box () [i] in the output loop below with box (), then the function in the loop is executed, and 5 anonymous function functions () {return i} are printed, so Here we have to pay attention to adding () to execute the anonymous function in the loop in order to actually output the number. So why is 5 5?

cause : Every time we output a loop, we execute the box () function, and each time it executes, the box function is executed, that is, in fact, each time the output loop is executed, the for loop executes 5 times in the box, that is, executes to i++=5, and each loop arr[i ]=5, so each output cycle results in 5. In fact, each output in the output cycle is the box function for the Loop 5 times after the result of 5, and box inside each loop, because the anonymous function is not self-executing, the result is anonymous function body. Only the fifth time, the result is 5.

Where does the problem arise? If the anonymous function is self-executing at the end of each loop, after each loop completes, it returns ARR, with 5 elements in the array being 0,1,2,3,4, then the 5 elements can be output sequentially in the next loop output. Specific solutions see 2. Direct parameter self-execution.

2. Direct parameter self-implementation

function box () {var arr=[];for (var i=0;i<5;i++) {arr[i]= (function (num) {return num;}) (i); The loop outputs}return arr by direct parameter self-implementation;  After self-execution, each cycle will return Arr}var B=box (), for (Var i=0;i<5;i++) {alert (B[i]),//here directly b[i], no more internal anonymous function}
here is the use of anonymous functions through the way of self-transfer, the implementation of the loop, in fact, the whole and the first way is the same, just a parameter implementation of the difference.

Return anonymous function in loop

function box () {var arr=[];for (var i=0;i<5;i++) {arr[i]= (function (num) {//num here return function () {//return a closed package return num;}    }) (i); Pass I to Num      }return arr;} var b=box (); for (Var i=0;i<5;i++) {alert (B[i] ());}

The third is by returning a closure, which if you use JS to step through debugging will find that its execution order and results are the same as the first. That is, the first execution box () returns 5 function, but after the last output loop execution, the result is shown as 0,1,2,3,4 here is the principle of using a closure to make the variable stay in memory, when executing the box () loop, it saves the variable I, and in the output, the output can be directly sequentially.

Summary: Through the closure to implement variables stored in memory, in many applications is very convenient, but because it occupies the memory, so in some use a lot of variables in the program, will affect the performance of the program execution, so the closure should be used with caution!



JS Basics-Closures

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.