VARs Variable Pre-parsing
In JavaScript, you can declare multiple var statements anywhere in a function, and they act as if they were declared at the top of a function, which is called hoisting (mount/sticky parsing/pre-parsing). A logic error can occur when you use a variable and then re-declare it in the function soon. For JavaScript, as long as your variable is in the same scope (the same function), it is treated as a declaration, even if it is used before the Var declaration. Look at the following example:
// Inverse Example 2 // global variable 3 function func () {4 // " Undefined "5 var myname =" local "; 6 // "local"7 }8 func ();
In this example, you might think that the first alert pops up "global" and the second pops up "Loacl". This may be understandable, because at the first alert, MyName did not declare that the function would naturally look at the global variable myname, but it does not actually work that way. The first alert pops up "undefined" because myname is treated as a local variable of the function (although it is later declared), and all variable declarations are suspended to the top of the function. Therefore, in order to avoid this confusion, it is best to pre-declare all the variables you want to use.
The code snippet above may perform the following behavior as follows:
1 // global variable2 function func () {3 var// equivalent to var myname = undefined; 4 // "undefined"5 myname = "local"; 6 // "local"}7 func ();
To be complete, let's mention something slightly more complex at the execution level. Code processing is divided into two phases, the first of which is the variable, function declaration, and the normal format of the parameter creation, which is a phase of parsing and entering the context. The second stage is code execution, function expressions and unqualified identifiers (for declared variables) are created. However, for practical purposes, we have adopted the concept of "hoisting", which is not defined in the ECMAScript standard and is often used to describe behavior.
http://www.nowamagic.net/librarys/veda/detail/1623
Http://www.cnblogs.com/jiajiayuan/archive/2013/02/04/2892061.html
Http://www.jb51.net/article/35542.htm
The Var in JS