JavaScript Learning Note: Closure (4)

Source: Internet
Author: User

Code:

1 varVal1=0;2 varVal2=0;3 varVal3=0;4 5  for(vari1=1;i1<=3;i1++){6     varI2=I1;7(function(){8         vari3=I2;9SetTimeout (function(){Tenval1+=I1; Oneval2+=I2; Aval3+=i3; -},1); -     })(); the } -  -SetTimeout (function(){ - Console.log (val1); + Console.log (val2); - Console.log (VAL3); +},100)

Question: Please write out the results of the code printed in this section.

Correct answer: 12,9,6

Parsing: Functions in settimeout Run after the code has run, because JavaScript is a single-process, event-looping mode, and settimeout is adding functions to the time loop queue after a set time. After joining the queue, you also need to wait for the currently executing function synchronization code to complete before you can perform functions that are joined to the queue by settimeout. Then look at I1,i2,i3, because Var is a function-level scope, so i3 in every anonymous function is redefined, its scope is only in the current anonymous function, so the last settimeout function used in the i3 is 1, 2, 3,i2 and I1 are located in the global scope, The difference is that i1 last more than I2, so the final value of I1 is 4,i2 the last value is 3. So val1=3*i1=12,val2=2*i2=9.

JavaScript Learning Note: Closure (4)

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.