As mentioned above, JavaScript does not have the syntax block similar to C # and Java. Variables defined in the for loop can still be used after the loop body is removed, for example:
Function Outputnumbers (count ){
For ( VaR I = 0 ; I < Count; I ++ ){
Alert (I );
}
Alert (I ); // Count
}
In addition, even if a variable is declared, and the variable is declared after the value is assigned, there will be no problem. js will ignore repeated declarations.
Function Outputnumbers (count ){
For ( VaR I = 0 ; I < Count; I ++ ){
Alert (I );
}
VaR I; // Variable redeclared
Alert (I ); // Count
}
In C # and Java, the syntax block is used to control the scope of variables. js cannot be used directly like this and a work und is required, for example:
( Function (){
// Block Code here
})();
The declaration of a function is surrounded by a pair of parentheses. Therefore, JS considers that parentheses are expressions, and variables within the expression range cannot be referenced externally, therefore, we can simulate the concept of similar blocks, such:
Function Outputnumbers (count)
{
( Function ()
{
For ( VaR I = 0 ; I < Count; I ++ )
{
Alert (I );
}
})();
Alert (I ); // Causes an error
}
The variables defined in the anonymous function are destroyed when the execution of the anonymous function ends. Therefore, they cannot be referenced outside, but the anonymous function can access count because the anonymous function forms a closure.
Benefits of using this method:
1. this method can effectively reduce the objects defined in the Global Context window. For pages developed by multiple users, it can reduce the occurrence of name conflicts, every developer can use the names they like without worrying about the global context window.
( Function (){
VaR Now = New Date ();
If (Now. getmonth () = 0 & & Now. getdate () = 1 ){
Alert ("Happy" New Year ! ");
}
})();
2. This method effectively reduces the memory issue of the closure, because it does not point to the reference of the anonymous function, so the anonymous function scope chain will be destroyed after the function is executed.