Take you to understand JavaScript closures

Source: Internet
Author: User
Tags closure

What is a closure package?
Look at the code first:

function A () {  var n = 0;  Function Inc () {    n++;    Console.log (n);  }  Inc ();   Inc (); }a (); Console output 1, then output 2

It's simple. Take another look at the code:

function A () {  var n = 0;  This.inc = function () {    n++;     Console.log (n);  };} var C = new A (); C.inc ();  Console output 1c.inc ();  Console Output 2

It's simple.

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 1c ();  Console Output 2

See how it's done:

var c = couter (), this sentence couter () 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!

All textbook tutorials like to use the last paragraph to illustrate closures, but I think it complicates the problem. This return is the function name, did not see the rectification-C + + program design students may suddenly not reflect the difference between the band (), that is, this writing comes with a trap. Although this kind of writing is more tall, but I still like to single the problem, look at code 1 and code 2, you will also tangle function calls, you will be entangled in the value of n?

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
Check this out:

function Createfunctions () {  var result = 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++) {  console.log (Funcs[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:

var result = new Array (), i;result[0] = function () {return i;}; No function is executed, the function is unchanged inside, and I cannot be replaced within the function! Result[1] = function () {return i;}; No function is executed, the function is unchanged inside, and I cannot be replaced within the function! ... result[9] = function () {return i;}; 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 to return 10console.log (i); FUNCS[1] () is the execution of the return I statement, which is to return 10...console.log (i); FUNCS[9] () is the execution of the return I statement, which is to return 10

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.

———————————————————————————————————————————————————————————————————————————————

This article reproduced from the script house, the original address: http://www.jb51.net/article/83524.htm

Take you to understand JavaScript closures

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.