Mimic block-level scopes
There is no concept of block-level scope in JavaScript, which means that the variables defined in the block statement are actually created in the containing function rather than in the statement.
1 function Outputnumbers (count) {2 for (var i = 0; i < count; i++) {3 console.log (i); 4 }5 console.log (i); 6 }
The local variable I defined in the for loop can then be accessed for out-of-loop, because the variable i is defined in the active object of outputnumbers (), so you can access it anywhere within the function, starting with its definition.
1 function Outputnumbers (count) {2 for (var i = 0; i < count; i++) {3 console.log (i); 4 }5 var i; 6 Console.log (i); 7 }
In this case, he will only turn a blind eye to subsequent statements. Anonymous functions can be used to mimic block-level scopes and avoid this problem.
1 (function() {2 /// This is block-level scope 3 });
The above code defines and immediately invokes an anonymous function. The function declaration is contained in a stack of parentheses, which means that it is actually a function expression. The other pair of parentheses immediately after it is called.
Attention:
1 function () {2 // This is a block level scope . 3 // Error
The function keyword represents the beginning of a functional declaration, and the function declaration cannot be followed by parentheses. However, the function expression can be followed by parentheses. To convert a function declaration into a function expression.
You can use a private scope wherever you need some variables temporarily
1 function Outputnumbers (count) {2 (function() {3for (var i = 0; i < count; i++) { 4 console.log (i); 5 }6 }) (); 7 // i am not defined 8 }
This technique is often used outside the function in the global scope to limit the addition of too many variables and functions to the global scope
1 (function() {2 varnew Date (); 3 if (Now.getmonth () = = 0 && now.getdate () = = 1) {4 alert ("Happy New Year"); 5 }6 }) ();
Where now is the local variable in the anonymous function, and we don't have to create it in the global scope.
function Expressions-mimic block-level scopes