JS Closure detailed

Source: Internet
Author: User

closure ( closure ) is Javascript a difficult language, but also its characteristics, many high-level applications are dependent on the implementation of closures.

Characteristics of closures

Closures have three properties:

1.函数嵌套函数2.函数内部可以引用外部的参数和变量3.参数和变量不会被垃圾回收机制回收
The definition of closure and its advantages and disadvantages

闭包is a function that has access to a variable in another function scope, the most common way to create a closure is to create another function within one function and access the local variables of the function through another function

The disadvantage of closures is that resident memory increases memory usage and is prone to memory leaks if used improperly.

Closures are javascript a major feature of language, the main application of closures is mainly to: design private methods and variables.

After the general function is executed, the local active object is destroyed and only the global scope is saved in memory. But the case of closures is different!

Closure of nested functions
function aaa () {    var a = 1;    return function () {   alert (a++)  };  }         var fun = aaa ();  Fun ();//1 after the execution of a++, and then a still in ~ fun  ();//2 Fun   = null;//a is recycled!!

closures cause variables to always be kept in memory, which increases memory consumption if used improperly.

javascriptPrinciple of garbage collection

(1), in javascript , if an object is no longer referenced, then the object will be GC recycled;
(2), if two objects refer to each other and are no longer referenced by the reference 3 , then the two objects referenced by each other are also recycled.

Benefits of using closures

So what are the benefits of using closures? The benefits of using closures are:

1.希望一个变量长期驻扎在内存中2.避免全局变量的污染3.私有成员的存在
The summation of global variables
var a = 1;function abc () {    a++;    alert (a);} ABC ();      2ABC ();    3
Second, local variables
Function abc () {    var a = 1;    a++;    alert (a);} ABC ();      2ABC ();   2

So how can you do variable A is both local and additive?

Third, the accumulation of local variables
function outer () {    var x=10;    return function () {    //function Nesting function            x + +;            alert (x);    }} var y = outer ();     The external function assigns the variable y;y ();                 The Y function is called once and the result is 11, which is equivalent to outer () (); Y ();                The Y function is called the second time, and the result is 12, which implements the cumulative
function declarations and function expressions

In JS we can function declare a function by the keyword:

Function abc () {    alert (123);} ABC ();

We can also turn this declaration into an expression by using a "()":

(function () {    alert (123);}) ();      The preceding expression is then called directly by (), so the function does not have to write a name;
Four, modular code, reduce the pollution of global variables
var abc = (function () {      //ABC is the return value of the external anonymous function    var a = 1;    return function () {            a++;            alert (a);    }}) (); ABC ();    2; Call an ABC function, in fact, call the inside function of the return value    ABC ();    3
V. The existence of private members
var AAA = (function () {    var a = 1;    function bbb () {        a++;        alert (a);    }    function CCC () {        a++;        alert (a);    }    return {        b:bbb,   //json structure        C:CCC    }}); aaa.b ();     2AAA.C ()      //3
Six. Using anonymous functions to implement accumulation
Implement the Add function box () {var age = 100;return function () {          /////anonymous functions Age++;return age;};} var b = Box () by using anonymous functions for local variables residing in memory; Lert (b ()); alert (b ());    Alert (Box ()), alert (b ()), alert (b)    ;     function () {            //   age++;           return age;       }b = null;  //dereference, waiting for garbage collection

Excessive use of closures can result in degraded performance. function, the closure is generated by the anonymous function in the

Find the index of the corresponding element directly in the loop
Window.onload = function () {    var aLi = document.getelementsbytagname (' li ');    for (Var i=0;i<ali.length;i++) {        Ali[i].onclick = function () {        ///When clicked for Loop has ended        alert (i);        }}    
Viii. using closures to rewrite the above code
Window.onload = function () {var aLi = document.getelementsbytagname (' li '); for (Var i=0;i<ali.length;i++) {        ( function (i) {            Ali[i].onclick = function () {                    alert (i);            };        }) (i);};
Nine. Memory leak issues

Because IE js objects and DOM objects use different garbage collection methods, closures IE can cause a memory leak problem, which means that elements residing in memory cannot be destroyed

 
function closure () {    var odiv = document.getElementById (' Odiv '),//odiv resides in memory after use    Odiv.onclick = function () {        alert (' odiv.innerhtml ');//use Odiv to cause memory leaks    };} Closure ();//The Odiv should finally be dereferenced to avoid memory leaks function closure () {    var odiv = document.getElementById (' Odiv ');    var test = odiv.innerhtml;    Odiv.onclick = function () {        alert (test);    };    Odiv = null;}

Ext.: http://segmentfault.com/a/1190000000652891

JS Closure detailed

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.