In JS we should try to avoid the use of global variables and global functions to prevent naming conflicts, then how to avoid it. JS has a concept of closure, now we use the closure of the block-level scope to explain, this is the closure of the most important concept.
JS itself is not supported like C/c#/java ... In such a language there is a block-level scope, that is, a variable defined in a syntax block that is inaccessible outside of the syntax block.
So, JS how to simulate a block-level scope like C. Let's look at a chestnut first:
For example:
Test ();
function test () {
() function () {for
(var i=0;i<3;i++) {
console.log (i);//This time I will be in the * * anonymous function in * * * * * * * * * Invalid anonymous function, I was destroyed outside the anonymous function
}
}) ();
Console.log (i);//output: undefined
}
Creating an anonymous function inside a function is equivalent to creating a private scope within a function, which is good for projects that are developed in larger/multiple people so that each programmer can use his or her own variables in their own functional functions without confusion or conflict.