Simple Understanding JS Closure

Source: Internet
Author: User

What is a closure package?
Let's look at a piece of code first:

function A () {        var n = 0;         function Inc () {            n+ +;            Console.log (n);        }        Inc ();        Inc ();    }     //

Take another look at the code:

  function A () {        var n = 0;          This function () {            n+ +;            Console.log (n);        };    }     var New a ();    C.inc ();   // Console Output 1
C.inc (); Console Output 2

What is a closure package? This is the closure!

A function that has access to a variable within the scope of another function is a closure. Here the INC function accesses the variable n in constructor A, thus forming a closure.

Take another look at the code:

function A () {        var n = 0;         function Inc () {            n+ +;            Console.log (n);        }         return Inc;    }     var c = A ();    C ();   // Console Output 1    C ();  // Console Output 2

See how it's done:

var C = A (), this sentence a () returns the function Inc, which is equivalent to var c = Inc;

C (), this sentence is equivalent to Inc (); Note that the function name is just an identifier (a pointer to a function) and () is the execution function.

The following three sentences are translated: var c = Inc;  Inc (); Inc (), is it different from the first piece of code? No.

What is a closure package? This is the closure!

Why do you write this?
We know that every function of JS is a small black house, it can get outside information, but the outside world can't directly see the content. Put the variable n into the small black room, in addition to the INC function, there is no other way to touch the variable n, and in the function a outside the definition of the same name variable n is not affected, this is called enhanced "encapsulation."

The reason to return the function with return is to identify Inc because the INC function cannot be called directly outside of the a function, so return Inc is associated with the outside, and this in Code 2 also links Inc to the outside.

Common pitfalls

 unction createfunctions () { var  Resul        t = new   Array ();  for  (var  i = 0; i <; I++) {Result[i]  = function   () { return   I;        };     return   result;     var  funcs = createfunctions ();  for  (var  i = 0; i < funcs.length; i+    +

At first glance, thought output 0~9, never thought output 10 10?

The trap here is this: the function band () is the execution function! a simple sentence of var f = function () {alert (' Hi ');}; is not to play the window, followed by a sentence F (); Code inside the function is executed. The above code translates:

varresult =NewArray (), i;result[0] =function(){returnI };//No function is executed, the function is unchanged inside, and I cannot be replaced within the function! RESULT[1] =function(){returnI };//No function is executed, the function is unchanged inside, and I cannot be replaced within the function! . .. result[9] =function(){returnI };//No function is executed, the function is unchanged inside, and I cannot be replaced within the function! i = 10; Funcs=Result;result=NULL; Console.log (i);//Funcs[0] () is the execution of the return I statement, which is the returnConsole.log (i);//Funcs[1] () is the execution of the return I statement, which is the return..... console.log (i);//Funcs[9] () is the execution of the return I statement, which is the return

Why did the garbage collect the result but not the I? Because I am still being referenced by the function. Like a restaurant, the plate is always limited, so the waiter will go to the counter to reclaim the empty plate, but also a dish of dishes he how dare to accept? Of course, you manually pour out the dishes (=null), the plate will be taken away, this is called the memory recovery mechanism.

As for the value of I can still retain, in fact, from the beginning of the article read down, this should have nothing to tangle with the place. Dishes inside the plate, eat a piece should not be a piece of it?

Summarize:

A closure is a variable in which a function refers to another function, because the variable is referenced so it is not recycled, so it can be used to encapsulate a private variable. This is the pros and cons, unnecessary closures will only increase memory consumption! also use closures to pay attention to whether the value of the variable matches your requirements, because he is like a static private variable. Closures are often mixed up with a lot of things to get to know more, and this is just a basic thing to talk about.

Simple Understanding JS Closure

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.