The statement set in any pair of curly braces belongs to one block. All variables defined in this block are invisible outside the code block, block-level scope is always the top priority of any programming language, because it controls the visibility and lifecycle of variables and parameters. Here, we first understand two concepts: block-level scope and function scope.
What is block-level scope?
The statement set in any pair of curly braces ({And}) belongs to a block. All variables defined in this block are invisible outside the block, which is called block-level scope.
The function scope is easy to understand (* ^__ ^ *). Parameters and variables defined in the function are invisible outside the function.
Most C classes have block-level scopes, but JS does not. See the following demo:
// C # include
Void main () {int I = 2; I --; if (I) {int j = 3;} printf ("% d/n", j );}
When you run this code, the error "use an undefined variable: j" will occur. As you can see, the C language has a block-level scope. Because j is defined in the if statement block, it cannot be accessed outside the block.
But how does JS behave? Let's look at another demo:
functin test(){ for(var i=0;i<3;i++){ } alert(i); } test();
Run this code and "3" is displayed. It can be seen that the variable I defined in the block is still accessible outside the block. That is to say, JS does not support block-level scopes. It only supports function scopes, and variables defined at any position in a function are visible anywhere in the function.
So how can we make JS have block-level scope? Do you still remember that the variables defined in a function will be destroyed after the function is called? Can we use this feature to simulate the block-level scope of JS? See the DEMO below:
function test(){ (function (){ for(var i=0;i<4;i++){ } })(); alert(i); } test();
If you run it again, an "I" undefined error will pop up ~~~ Here, we place the for statement block in a closure, and then call this function. When the function call is complete, variable I is automatically destroyed, so we cannot access the block.
The closure feature of JS is the most important feature (* ^__ ^ *) that everyone understands ). In JS, to prevent name conflicts, we should avoid using global variables and global functions. So how can we avoid it? Yes, as shown in the demo above, we can put all the content to be defined into
(Function () {// content })();
At this time, do we add a function scope to their outer layers? Programs outside the scope cannot access them.