JS Closed Package

Source: Internet
Author: User

closures are functions that have access to variables in another function scope.

Here are some of the simplest small examples:

1 //This is a basic example of closures2 3 functionOutter () {4     5     vartemp = 0;//no VAR is a global variable! 6 7     functioninner () {8   9         return++temp;//1. Use another (external) function variableTen  One     } A  -     returnInner//2. Returns a reference to an intrinsic function - } the  - varTest = Outter () ();//3. Calling functions -  -Console.log (test);//Output: 1

Is it possible for a god horse to take a local variable of a function?

First of all, the JS memory recovery mechanism: When the function executes, its defined variables are stored in the memory space, and so the function is completed, the variables destroyed memory release. But what if another function is nested inside the function? automatically saves the function along with the variables he might use, including local variables and variables of the parent and ancestor functions (free variables). That is, to build a closure, these variables will not be recycled by the memory collector, only if the internal function is not possible to be called later (for example, deleted or without pointers) , the closure is destroyed, and none of the variables referenced by the closure are recycled when the next memory recycle starts.

Here are a few things to note:

Scenario 1: see Example

1 /*This is the example of http://www.cnblogs.com/mzwr1982/archive/2012/05/20/2509295.html, I am too lazy, borrow, hehe ~2 */3 varresult=[];4 5 functionfoo () {6     vari= 0;7 8      for(; i<3;i=i+1){9 //The highlights come in, and this inside I is actually a reference to the outer loop iTenresult[i]=function(){ One alert (i) A         } -     } - }; the  - foo (); -Result[0] ();//3 -RESULT[1] ();//3 +RESULT[2] ();//3 -  + //the correct wording is as follows A varresult=[]; at  - functionfoo () { -     vari= 0; -      for(; i<3;i=i+1){ -Result[i]= (function(j) { -             return function(){ in alert (j); -             }; to }) (i); +     } - }; the  * foo (); $Result[0] ();//0Panax NotoginsengRESULT[1] ();//1 -RESULT[2] ();//2

The same examples include:

1Window.onload =function ()2 3 {4 5     varOLi = document.getElementsByTagName ("li");6 7      for(vari = 0; i < oli.length; i++)8 9     {Ten  OneOli[i].index =i; A  -Oli[i].onclick =function() { -  theConsole.log (Oli[i].index);//I can't do it directly, OH ~ -  -         }; -  +     }     -  +}
View Code

Situation Two:

1 varName = "the window";2 3 varObject = {4Name: "My Object",5 6Getnamefunc:function(){7 8             varthat = This;//the This of the anonymous function is a global variable, so ...9 Ten             return function(){ One          A                 returnThat.name;//if the this.name is actually the Window, now we expect the My Object -  -             }; the       } -};

Scenario three (also known as memory leak):

If the scope chain of a closure contains an HTML element, the element cannot be destroyed, such as:

function example () {     var ele = document.getElementById ("someelement");      function () {                   console.log (ele.id); // cannot be freed      }};

The improvement code is as follows:

1 functionexample () {2      varEle = document.getElementById (' someelement '));3      varID =ele.id;4      5Ele.onclick =function(){6 Console.log (ID);7      };8 9Ele =NULL;Ten};

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.