What is a closure (closure) and why use it?

Source: Internet
Author: User

Closures are functions that have access to variables in another function scope, and the most common way to create closures is to create another function within one function, access the local variables of the function through another function, and use closures to break through the scope of the action and pass the variables and methods inside the function to the outside.

characteristics of closures:

1. Nested functions within functions
2. Intrinsic functions can refer to the outer parameters and variables
3. Parameters and variables are not recycled by the garbage collection mechanism

Html:

<!--The onclick event of the Li node will correctly eject the currently clicked Li Index.
<ulID= "Testul">    <Li>index = 0</Li>    <Li>index = 1</Li>    <Li>index = 2</Li>   <Li>index = 3</Li></ul>

Js:

<script type= "Text/javascript" > var nodes = document.getelementsbytagname ("li");  for (i = 0;i<nodes.length;i+= 1= (function(i) {  return   function// without closure, the value is 4} each time  ) (i); }</script>


Then we look at the following piece of code, which is a very straightforward description of the closure function:

function  say667 () {//  Local variable that ends up within closurevar num = 666;   varfunction() {alert (num);  } num+ +;  return  Sayalert;} var sayalert = say667 (); Sayalert ()// execution Results should pop up 667  

After executing say667 (), the say667 () closure internal variable will exist, and the inner variable of the inner function of the closure will not exist
Make JavaScript garbage collection mechanism GC does not reclaim resources occupied by say667 ()
Because the execution of the intrinsic function of say667 () relies on the variables in the say667 ()

What is a closure (closure) and why use it?

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.