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.