As long as you write a bit of JS code, very simple a var is finished. What happened to the JS compiler behind it? Then step by step through the code.
Copy Code code as follows:
x = 1;
alert (x);
var y = function () {
alert (x);
var x = 2;
alert (x);
}
Y ();
The code above will also get you the correct one. It will output separately: 1,undefined,2. For me, the first reaction it will output: 1,1,2. Why does the second one output undefined? In the above I have clearly defined a global variable x, why can't I find it?
That is because: the JS compiler in the execution of this y function, will put the body inside the declaration variable ahead of the declaration to the front. For example: Var x=2; The compiler first makes the Var x declaration in front of the body. In fact, the above code is equivalent to the following code:
Copy Code code as follows:
x = 1;
alert (x);
var y = function () {<br>var x;//x is not assigned at this time, so undefined.
alert (x);
x = 2;
alert (x);
}
Y ();
So it is not difficult to understand the x=undefined. But if you put var x = 2; This code is deleted, internally it does not have a VAR declaration. It will always look up in the scope, at which point X is Global X.
Now let's look at a more interesting example.
Copy Code code as follows:
var a = 1;
Function B () {
A = 10;
Return
}
b ();
alert (a);
///////////////////////////////////
var a = 1;
Function B () {
A = 10;
Return
function A () {}
} b (); alert (a);
The example is simple. The first example is output 10, and the second output is 1. What is this for? And the second example I return. Should be supposed to output 10 is right Ah! At that time because the JS compiler behind the mischief.
The difference between the two pieces of code is the second example of a function A () {}, and there is nothing in the body of it, and no calls are made to it.
In fact, the JS compiler in the back will function A () {} compiled into Var a=function () {}. At this time there is also a a=10 inside the function; The outside of a is also 1; according to JS scope. You'll find the internal a, if you can't find it up to the first level.
The most alert (a) will show 1;