We know that JS variables should be defined by VAR, for example:
VaRA;
This definition only defines the variable name, but does not give the initial value. However, JS automatically assigns the undefined initial value during compilation. If you want to give a clear initial value, you can define it as follows:
VaRA = 123;
See the followingCode:
Alert ();VaRA = 123;
The above code used variables before var. We generally think thatProgramAn error is reported. However, after running the program, alert outputs undefined (undefined is also a value ). Why?
Before answering this question, let's look at the following code:
Alert (a);= 123;
The difference between this code and the previous Code is that the VaR keyword is removed. However, after running the program, we found an error. Why?
To answer this question, we must understand some internal mechanisms of Js. This tutorial is very detailed.
First, we know that JS has nothing but objects. So what is the above variable? In fact, in <SCRIPT>... </SCRIPT> the VaR directly written under the tag (not in the function) is called the top-level variable. However, the top-level variable should not be called a variable, but an attribute of the window object. When the window object parses the <SCRIPT>... </SCRIPT> label in the browser, it automatically finds the variable defined by VAR, and immediately acts as an attribute of the window and initializes it as undefined. In addition, even if the initial value is given during var definition, the new property of window is still initialized as undefined.
Let's look at the previous Code:
Alert ();VaRA = 123;
After this code is parsed, it is equivalent to the following:
VaRA; alert (a);= 123;
Therefore, we can see that the alert output is undefined.
Let's look at another piece of code above:
Alert (a);= 123;
No var keyword is found when this code is parsed. Therefore, when you execute alert (a), it is equivalent to executing alert (window. a), and the window object does not have the attribute. Of course, an error is returned.
Again, please read this tutorial carefully. At the same time, please read the previous and subsequent chapters carefully. I believe it will be of great help for you to improve Js.