One minute to understand JS closure _javascript skills

Source: Internet
Author: User
Tags closure

What is a closure?
first look at a piece of code:

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

It's easy. Let's look at a piece of code:

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

It's easy.

What is a closure? This is the closure!

Functions that have access to variables within another function scope are closures. Here the INC function accesses the variable n in constructor A, so a closure is formed.

Let's look at a piece of 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

Let's 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 identity (pointing to 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 paragraph of code? No.

What is a closure? This is the closure!

All textbook tutorials like to use the last paragraph to illustrate closures, but I think this complicates the problem. This return is the function name, did not read Tan Haoqiang C + + program design students may not react out of the band without () the difference, that is, this type of writing with a trap. Although this kind of writing is more tall, but I still like the problem single, look at code 1 and code 2, you will also tangle function calls, you will tangle N value?

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

The reason to return function Identification, Inc., is because it is not possible to call the INC function directly outside of the A function, so returns Inc is associated with the outside, and this in Code 2 also links Inc to the outside.

A common pitfall
look at this:

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, think output 0~9, never thought output 10 10?

Here's the trap is: function with () is the executive function! the simple word var f = function () {alert (' Hi '); is not going to play the window, followed by an F (); The code inside the function is executed. The above code translation is:

var result = new Array (), I;
Result[0] = function () {return i;}; The function is not executed, the function inside is invariant, I cannot replace the inside of the function!
Result[1] = function () {return i;}//No functions, function internal unchanged, cannot replace I in function!
...
RESULT[9] = function () {return i;}; The function is not executed, the function inside is invariant, I cannot replace the inside of the function!
i = ten;
Funcs = result;
result = NULL;

Console.log (i); Funcs[0] () is the execution return I statement, is returns ten
console.log (i);//funcs[1] () is the execution return I statement, is returns ten
...
Console.log (i); FUNCS[9] () is to execute return I statement, that is, returns 10

Why does garbage recycle result, but not accept I? Because I'm still being referenced by a function. Like a restaurant, the plate is always limited, so the waiter will go to the patrol to collect the empty plate, but still have a dish of dishes how dare he accept? Of course, you manually emptied the dish (=null) and the plate was taken away, which is called the memory recycle mechanism.

As to how the value of I can still be retained, actually read from the beginning of the article, this should have nothing to tangle place. The dishes inside the dish, eat a piece should not be less?

To sum up
A closure is a variable in which a function references 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 advantage is also a disadvantage, unnecessary closures will only increase memory consumption! also use the closure to notice whether the value of the variable meets your requirements because he is like a static private variable. Closures usually mix with a lot of things to get a little more understanding, and here's just a start to talk about basic things.

This article link: http://www.cnblogs.com/qieguo/p/5457040.html

The above is the entire content of this article, I hope to help you learn.

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.