A preliminary understanding of JavaScript closures

Source: Internet
Author: User

1. A simple example

First, from a classic error, there are a number of div on the page, we want to bind them an onclick method, and then have the following code

 <ulID= "Divtest">        <Li>0</Li> <Li>1</Li> <Li>2</Li> <Li>3</Li> </ul><ulID= "DivTest2">        <Li>0</Li> <Li>1</Li> <Li>2</Li> <Li>3</Li> </ul>

Initial implementation:

var div = document.getElementById ("divtest");     var spans = div.getelementsbytagname ("li");      for (var i = 0; i < spans.length; i++) {        function  () {            console.log (i);        }    

Result: The display is all 4, not the expected result, the desired 0,1,2,3,

Make the following changes to get the desired results

   var div2 = document.getElementById ("DivTest2");     var spans2 = div2.getelementsbytagname ("li");      for (var i = 0; i < spans2.length; i++) {        (function  (num) {              function  () {                console.log (num);            }        }) (i);    

2. The reason

The first way, after the page load will be executed, when the value of I is 4, the judgment condition is not established, the for loop execution, but because each Li's OnClick method is an intrinsic function, so I was closed reference, memory can not be destroyed, I value will remain 4, It will not be recycled until the program changes it or all of the onclick functions are destroyed (by actively assigning the function null or page unloading).

So every time we click on Li, the onclick function looks for the value of I (the scope chain is a reference), a check equals 4, and then it shows to us.

The second way is to use an immediately executed function and create a layer of closure, the function declaration is placed in parentheses into an expression, followed by parentheses and parentheses is called, at this time I when the argument passed, the function is immediately executed, Num saves the value of I.

A preliminary understanding of JavaScript closures

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.