Used to be directly bootstrap the front-end frame, suddenly want to look at JavaScript, found that JavaScript is a very interesting thing, here is the first encounter of a small problem of the understanding of the next record (not much nonsense, on the code).
/** * Example 1*/varLocalvar = "Local var"; Console.log (Localvar);//local var/** * Example 2*/Console.log (x= = = undefined);//truevarx = 3;/** * Example 3*/varMyVar = "My Value";//Test01//Would return a value of undefined(function() {console.log (myvar);//undefined varMyVar = "Local value"; Console.log (MyVar); //Local Value}); Console.log (MyVar) ;//My value//Test02(functionmyFunction () {console.log (myvar);//My value})();//Test03varTest =New function() {console.log (myvar);//My value};
The explanations are as follows:
(1). The special point of a JavaScript variable is that you can refer to a variable declared later without throwing an exception. This concept is called variable Declaration elevation (hoisting);
(2). JavaScript variables feel like they are "lifted" or moved to the top of a function or statement. However, the promoted variable will return the undefined value.
(3). When a variable is declared and initialized after it is used or referenced, the promoted reference will still get the undefined value.
(4). Here Example 3 Test01 is the key to this problem, Test01 and Test02 are very similar (at least I look very similar). But the final output cannot be explained by (1), (2), (3).
After viewing the official API documentation found, the anonymous function (function() {}) (), the use of the formation of closures (emphasis, unclear can see the concept of closure, closure concept is still good understanding);
Due to the existence of closures, global variables are naturally inaccessible (one of the important reasons for closures is to avoid accessing global variables), so the first sentence in Test01 function outputs the result of undefined.
Summary Reason: Anonymous functions (function() {}) (); is a special closure notation.
Anonymous functions in JavaScript ((function () {}) ();) and scope of variables