Scope is always the most important in 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 a block-level scope?
The set of statements in any pair of curly braces ({and}) belongs to a block, in which all the variables defined are not visible outside the code block, which we call block-level scopes.
The function scope is well understood (*^__^*), and the parameters and variables defined in the function are not visible outside the function.
Most Class C languages have block-level scopes, but JS does not. Please see demo below:
C language
#include
void Main ()
{
int i=2;
i--;
if (i)
{
int j=3;
}
printf ("%d/n", j);
}
Run this code, there will be "use a undefined variable:j" error. As you can see, the C language has a block-level scope, because J is defined in the statement block of if, so it is inaccessible outside the block.
And JS is how to behave, and then look at another demo:
Functin Test () {
for (Var i=0;i<3;i++) {
}
alert (i);
}
Test ();
Run this code, pop "3", visible, outside the block, the variables defined in the block I are still accessible. That is, JS does not support block-level scopes, it only supports function scopes, and variables defined anywhere in a function are visible anywhere in the function.
So how do we make JS have block-level scopes? Remember, the variables defined in a function, when the function is called, the variable will be destroyed, can we use this feature to simulate the block-level scope of JS? Look at this demo:
function Test () {
(function () {
for (Var i=0;i<4;i++) {
}
})();
alert (i);
}
Test ();
Run again at this time, will pop up "I" Undefined error, Haha, come true ~ ~ ~ Here, we put the for statement block in a closure, and then call this function, when the function call finished, the variable I automatically destroy, so we can not access the block outside.
The closure feature of JS is the most important feature (*^__^*) that everyone understands. In JS, in order to prevent naming conflicts, we should try to avoid using global variables and global functions. So how do we avoid it? Yes, as shown in the demo above, we can put everything we want to define into a
(function () {
Content
})();
, is this the equivalent of adding a function scope to their outer layers? Programs outside of this scope cannot access them.