JavaScript----Closures (what are closures, why closures, the role of closures)

Source: Internet
Author: User
Tags variable scope

Often asked what is closures?

To be honest, the concept of closures is difficult to explain. In the JavaScript authoritative guide, there is a phrase: "JavaScript functions are the code that will be executed and a complex that executes the scope of these code." In computer science, this code and the scope of the sum complex are called closures. ”。 The implication is that all JavaScript functions are closures.

Some people will say that this explanation is not right. We often say closures should look like the following string of code:

    var function () {        var a=1;         return function F2 () {            a+ +;            Alert (a)        }    }    var b = F1 ();    b ();             // 2    b ();            // 3

Yes, this is a classic example of closures, and is what we usually call closures. In this code, B is the function of the closure F2.

Why use closures?

Writing here, we have to understand the special variable scope of JavaScript and the garbage collection mechanism of JavaScript.

(1), what is a variable scope? The scope of a variable is the area of the first variable in the program. JavaScript variables are divided into "global variables" and "local variables".

Global variables: Global variables are scoped globally, meaning that they are defined everywhere in JavaScript code. I often write a "a=1", the variable "a" is defined as a global.

Local variables: variables declared within a function are defined only within the body of the function, and its scope is local. The parameters of the function are also local variables, which are defined only within the function body. In the body of a function, a local variable takes precedence over a global variable of the same name, for example:

var a =1;     function F1 () {        var a=2;        alert (a);    }     // 2

So if I turn the variable "a" into a local variable, for example:

function F1 () {        var a=2;    }    

It will be reported as error:

Some people will say, how can there be such a wonderful demand, below I give an example, we will find that, in fact, we still used.

Closure instances:

When I "click" the button, the effect is as follows:

Code we might be dealing with:

$ ('. Button '). Click (function(){        varLength = $ ('. List '). Find (' Li '). length; varTimer =NULL;  for(vari=0;i<length;i++) {Timer=settimeout (function(){                if(i>length)                {clearinterval (timer); }                $('. List li '). EQ (i). css ({'-webkit-transform ': ' Scale (' + (i+1) + ') ', ' marginleft ':(i+1) *50 + ' px '}) Console.log (i)},i*2000)        }    })

After running you will find that there is no effect we want to print "I", found, how will output 3 times "3" is actually a for () inside the scope of the variable i, I scope only in the function of the For loop in the body, how to achieve this effect, we can make a small change, The code is as follows:

$ ('. Button '). Click (function(){        varLength = $ ('. List '). Find (' Li '). length; varTimer =NULL;  for(vari=0;i<length;i++) {Timer=settimeout ((function(i) {if(i>length)                {clearinterval (timer); }                $('. List li '). EQ (i). css ({'-webkit-transform ': ' Scale (' + (i+1) + ') ', ' marginleft ':(i+1) *50 + ' px '})                //Console.log (i)}) (i), i*2000)        }    })

Put "I" as a parameter, which makes up the closure.

(2), what is the garbage collection mechanism of javascript?

A: JavaScript does not require manual release of memory, it uses a method called garbage collection, and the JavaScript interpreter can detect when a program no longer uses an object. When it is determined that an object is useless, the JavaScript interpreter frees the memory occupied by the object.

So in summary, it is not difficult to understand that in the F1 function to define a local variable A, outside the F1 function, the variable A will not be found, because it was released.

Is it possible for us to think that "the function (or definition) of a closure is to allow a private variable (or a local variable) to be shared by multiple functions without being automatically freed from memory by the parser of the JavaScript ?"

The disadvantage of closures: because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.

Building, the understanding of the closure of the current so much, and so in-depth study, will be supplemented and amended. Recommend that you can see "Ruan Yi Feng" teacher wrote "learning JavaScript closure (Closure)", Link: http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html

JavaScript----Closures (what are closures, why closures, the role of 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.