Sample parsing of the principles behind JavaScript var declarations of variables

  • 2020-03-26 21:25:43
  • OfStack

As long as you've written a little bit of JS code, it's a simple var thing. So what happens to the JS compiler after it's back? So let's go step by step through the code.
 
x = 1; 
alert(x); 
var y = function() { 
alert(x); 
var x = 2; 
alert(x); 
} 
y(); 

The code above will also -- you got it right it will print: 1,undefined,2. For me, the first reaction is going to be 1,1,2. Why does the second output undefined? I explicitly defined a global variable up here, x. Why can't I find it?

That's because when the js compiler executes the y function, it puts the declaration variable inside the body in front of it. For example, var x=2; The compiler starts with the var x declaration before the body. In fact, the above code is the same as the following code:
 
x = 1; 
alert(x); 
var y = function() {<BR>var x;//X is not assigned yet, so it's undefined.
alert(x); 
x = 2; 
alert(x); 
} 
y(); 

So it's not hard to understand that x is undefined, but if you take the var of x is equal to 2; This code was deleted, and it didn't declare var internally. It's going to go all the way up the scope, where x is global x.
Now let's do a more interesting example.
 
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 outputs 10, and the second outputs 1. Why is that? And I've returned the second example. In principle should output 10 just right! That was because the JS compiler was behind it.
Function a(){}; There is nothing in the body of the function, and no calls are made to it.

In fact, the JS compiler will compile function a() {} in the background to var a=function (){}. And then for the inside of the function we also have a is equal to 10; Some of the a's out there are still 1's; According to the JS scope. I'm going to look for the internal a first, and if I can't find it, I'm going to go up to the next level.
The most alert(a) will show 1;

Related articles: