The first parameter of setTimeout () is the deep understanding of the string and the eval function.

Source: Internet
Author: User
1 <script language="javascript" type="text/javascript"> 2   var a=1;3   setTimeout(‘var a=2;alert(a)‘, 1000);4   alert(a);5   setTimeout(‘alert(a)‘,1000);6 </script>
//1 2 1;

I will not explain too much about setTimeout Asynchronization here (about how to add asynchronous callbacks to event queues). I will focus on the notes when a parameter is a string.

From the code above, we can see that when the first parameter of setTimeout is a string, it is actually equivalent to a variable defined by a new function in the function, which is equivalent:

1  <script language="javascript" type="text/javascript"> 2      var a=1;3      setTimeout(function(){var a=2;alert(a);}, 1000);4      alert(a);5      setTimeout(function(){alert(a);},1000);6 </script>7 //1 2 1;
1 <script language="javascript" type="text/javascript"> 2     var a=1;3     new Function(‘var a=2;alert(a);‘);4     alert(a);5     new Function(‘alert(a);‘);6 </script>7 //1 2 1;

But this is not the case for eval functions.

1 <script language="javascript" type="text/javascript"> 2     var a=1;3     eval(‘var a=2;alert(a)‘);4     alert(a);5     setTimeout(‘alert(a)‘,1000);6 </script>  
//2 2 2;

The eval function will directly define the strings in it to the global, and will not be defined in a closure function like setTimeout and new function. Therefore, the eval function will not only have the risk of XSS attacks, there will also be global variable pollution, so we should try to reduce the use of multiple eval as much as possible. It is also feasible to replace eval with the new function when there is no need to use it.

The first parameter of setTimeout () is the deep understanding of the string and the eval function.

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.