A detailed explanation of the graphic code of JavaScript closures in one minute

Source: Internet
Author: User
All the functions that have the right to access variables in another function scope are closures. Here, the inc function accesses the Variable n in constructor a and forms a 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 (); // The console outputs 1 and 2.

Simple. Let's take a look at the Code:

Function a () {var n = 0; this. inc = function () {n ++; console. log (n) ;};} var c = new a (); c. inc (); // The console outputs 1c. inc (); // console output 2

Simple.

What is a closure? This is the closure!

All the functions that have the right to access variables in another function scope are closures. Here, the inc function accesses the Variable n in constructor a and forms a closure.

Let's take a 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

Let's see how it is executed:

Var c = couter (), the 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 only an identifier (pointer to the function), and () is the execution function.

Var c = inc; inc (); is it different from the first code? No.

What is a closure? This is the closure!

All textbooks use the last section to describe the closure, but I think this will complicate the problem. The function name is returned here. Those who have not read tan haoqiang's C/C ++ programming may not suddenly reflect the difference with no (). That is to say, this writing method comes with a trap. Although this writing method is more advanced, I still like to unify the problem. If you look at code 1 and Code 2, you will also struggle with function calls. Will you tangle with n values?

Why?

As we know, every function in js is a small black house, which can obtain external information, but the outside world cannot directly see the content in it. Put Variable n into the dark room. Except for the inc function, there is no other way to access Variable n. Besides function a, defining variable n with the same name does not affect each other, this is the so-called "encapsulation" enhancement ".

The reason why the return function mark inc is used is that the inc function cannot be directly called outside function a, so return inc is associated with the outside, this in Code 2 also Associates inc with the external.

Common traps

Look at this:

function createFunctions(){    var result = new Array();    for (var i=0; i < 10; 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, the output is 0 ~ 9, never expected to output 10 10?

The trap here is: The function band () is the execution function! A simple var f = function () {alert ('Hi') ;}; the window will not pop up, followed by an f (); to execute the code inside the function. The above code is translated as follows:

Var result = new Array (), I; result [0] = function () {return I ;}; // The function is not executed and remains unchanged inside the function, I in the function cannot be replaced! Result [1] = function () {return I ;}; // The function is not executed and remains unchanged inside the function. You cannot replace the I in the function !... Result [9] = function () {return I ;}; // The function is not executed and remains unchanged inside the function. You cannot replace the I in the function! I = 10; funcs = result; result = null; console. log (I); // funcs [0] () is to execute the return I statement, that is, to return 10console. log (I); // funcs [1] () is to execute the return I statement, that is, to return 10... console. log (I); // funcs [9] () is to execute the return I statement, that is, to return 10

Why is I not collected after only garbage collection? Because I is still being referenced by function. For example, in a restaurant, there is always a limited number of dishes, so the waiter will go to the patrol station to recycle empty dishes, but how can he accept dishes? Of course, if you manually drop the dishes (= null) in the plate, the plate will be taken away. This is the so-called memory recycle mechanism.

As for how the I value can be retained, in fact, there should be nothing to worry about from the beginning of the article. Should I have one less dish?

To sum up

A closure is the variable that a function references to another function. Because the variable is referenced, It is not recycled. Therefore, it can be used to encapsulate a private variable. This is both an advantage and a disadvantage. Unnecessary closures only increase memory consumption! In addition, when using closures, pay attention to whether the value of the variable meets your requirements, because it is like a static private variable. Closures usually mix and match with many things. If you have more contact with each other, you can get a better understanding of things. Here we just start to talk about the basic things.

The above is a detailed explanation of the graphic code that takes you one minute to understand JavaScript closures. For more information, see other related articles in the first PHP community!

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.