Javascirpt: how to simulate the block-level scope (js elevation note) and duplicate cirpt elevation
Because javascript does not have block-level scope, the variables defined in block statements are actually created in functions rather than statements.
For example:
function outputNumbers(count){ for(var i=0; i< count; i++){ alert(i); } alert(i);}
This function defines a for loop, and the initial value of variable I is set to 0. In Java, C ++, and other languages, variable I is defined only in the statement block of the for loop. Once the loop ends, variable I will be destroyed. However, in Javascript, variable I is defined in the outpuNumbers () activity object. Therefore, from its definition, it can be accessed within the function. Even if you mistakenly declare the same variable as below, it will not change its value.
Function outputNumbers (count) {for (var I = 0; I <count; I ++) {alert (I) ;} var I; // re-declare the variable alert (I); // count}
Javascript will never tell you whether to declare the same variable multiple times. In this case, it will turn a blind eye to the subsequent declaration, but will execute variable initialization in subsequent declaration. Anonymous functions can be used to simulate block-level scopes and avoid this problem.
(Function () {// here is the block-level scope })()
The code above defines and calls an anonymous function immediately. Include the function declaration in a pair of parentheses, indicating that it is actually a function expression. The other pair of parentheses following it will immediately call this function,
Another method:
Var someFunction = function () {// This is a block-level scope}; someFunction ();
The preceding example defines a function and calls it immediately. You can define a function by creating an anonymous function and assigning an anonymous function to the variable someFunction. The method for calling a function is to add a pair of parentheses after the function name, but note that the function value cannot replace the function name, as shown in figure
Function () {// here is the block-level scope }();
This will lead to syntax errors, because Javascript regards the function keyword as the beginning of a function declaration, and the function declaration cannot be followed by parentheses. The expression can be followed by parentheses.