For example, the following code
Copy codeThe Code is as follows:
{
Var temp = "12 ";
}
Alert (temp); // OUTPUT 12
According to the general programming experience, the alert function cannot access the temp variable because it is in another block, but in JavaScript, there is no block scope concept, therefore, this syntax does not work for Javascript, but when we write javascript programs, especially large programs or libraries, to prevent name conflicts, another mechanism to control the scope of variables is required. So here we introduce a common method to implement the concept of block scope. The Code is as follows:
Copy codeThe Code is as follows:
(Function (){
Var temp = "123 ";
})();
Alert (temp); // Output Error
The code above defines a function expression and calls it immediately. This form imitates the block scope concept and protects the namespace in the block, this method is useful in some large libraries.
(For example, JQuery) effectively avoids name conflicts. In fact, JQuery uses this method to implement block scope.