Scope is always the top priority in any programming language because it controls the visibility and life cycle of variables and parameters. Speaking of this, first understand two concepts: block-level scope and function scope.
What is a block-level scope?
The statement set in any pair of curly braces ({and}) belongs to a block, and all variables defined in this are invisible outside the code block, which we call block-level scope.
The scope of the function is easy to understand (*^__^*), and parameters and variables defined in the function are invisible outside the function.
Most C-class languages have block-level scopes, but JS does not. Please see the demo below:
//C language#include <stdio.h> void main() { int i=2; i--; if(i) { int j=3; } printf("%d/n",j); }When running this code, an error of "use an undefined variable:j" will appear. As you can see, 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 how does JS perform, let’s look at another demo:
functin test(){ for(var i=0;i<3;i++){ } alert(i); } test();Run this code and "3" pops up. It can be seen that outside the block, the variable i defined in the block is 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 that function.
So how do we make JS have a block-level scope? Do you still remember that when the variable defined in a function is called, the variable will be destroyed? Can we use this feature to simulate the block-level scope of JS? Look at the following DEMO:
function test(){ (function (){ for(var i=0;i<4;i++){ } })(); alert(i); } test();Run it again at this time, an undefined error of "i" will pop up. Haha, it's implemented~~~ Here, we put the for statement block into a closure and call this function. When the function call is completed, the variable i will be automatically destroyed, so we cannot access it outside the block.
The closure feature of JS is the most important feature((*^__^*) Everyone understands). In JS, in order to prevent naming conflicts, we should try to avoid using global variables and global functions. So, how to avoid it? OK, as shown in the above demo, we can put everything we want to define into one
(function (){ //Content})();Among them, at this time, is it equivalent to adding a function scope to their outer layer? Programs outside of this scope cannot access them.