Scope has lexical scope and block-level scope, JavaScript belongs to lexical scope, but in Java, C + + is a block-level scope. In JavaScript, only functions are able to create scopes, scoped by function.
Look at the code first:
function OutPut () { for (i=0;i<5;i++) { console.log (i); // 0,1,2,3,4 First I } console.log (i); // 5 A second I};
Explanation: In languages such as Java, the I variable in the For loop code is destroyed, and the second I prints out is undefined because they are block-level scopes. If you need to make the second I inaccessible to the first I, you need to mimic the block-level scope!
As I said just now, in JavaScript, only functions can create scopes, so block-level scopes need to be created with functions. The usual practice is to implement it through anonymous functions, as follows:
(function() { //}) ();
Explanation: JavaScript mimics the block-level scope in fact very simple! But for some of the poor students may still not very good understanding, we take it apart to see.
var fn=function() { // omit a piece of code };FN ();
This is a very common code for function definition and invocation. In JavaScript, a function is a class object, so a function can be passed as a value or a parameter (an aside: A callback function can be implemented when the function is placed as a parameter in another function), where the anonymous function is assigned to the variable FN, and then the function FN is executed with a parenthesis ().
From the above we might think: directly with anonymous function functions () {...} Do you want to replace FN to do it? So there's the following code:
function (){... //uncaught SyntaxError} ();
However, this is the wrong wording. Because the anonymous function is just a function declaration, the function declaration is not enough to perform the function, what if I want it to execute? We can make a function declaration into a function expression by some means, so that the function can be executed, and the common notation is to use () parentheses to wrap the anonymous function ()!
There is another, more accurate term for this JavaScript notation: The immediately called function expression (iife). As the name implies: it is a function expression, can be executed immediately! I'll explain it in more depth in the next blog post.
JavaScript mimics block-level scopes