In JavaScript, you can declare multiple var statements at any position of the function, and they serve as if they were declared at the top of the function, this behavior is called hoisting (mounting/top resolution/pre-resolution ). When you use a variable and then re-declare it in the function, logical errors may occur. For JavaScript, you only need that your variables are in the same scope (the same function) and they are declared, even when they are used before the VaR declaration. Let's look at the example below:
// Counterexample myname = "Global"; // global variable function func () {alert (myname); // "undefined" Var myname = "local"; alert (myname ); // "local"} func ();
In this example, you may think that the first alert is "Global" and the second alert is "loacl ". This expectation is understandable, because at the first alert, myname was not declared. At this time, the function will naturally look at the global variable myname. However, this is not actually the case. The first alert will pop up "undefined" because myname is treated as a local variable of the function (although declared later), and all the variable declarations will be mounted to the top of the function. Therefore, to avoid such confusion, it is best to declare all the variables you want to use in advance.
The execution of the above code snippet may be like the following:
Myname = "Global"; // global variablefunction func () {var myname; // equivalent to-> var myname = undefined; alert (myname ); // "undefined" myname = "local"; alert (myname); // "local"} func ();
Domain parsing: var Distribution