The scope of variables defined by var in JScript does not remember when the JScript syntax tutorial was read. It is completely legal to ignore the var keyword when declaring a variable. At that time, because JavaScript was thought to be the loosely-typed language, var may be a decoration. However, facts often prove that the result is unreliable.
Let's take a look at the results of the following examples to find out the problem:
No.1
<Script language = "javascript"> var var00 = 0; document. write (var00 + ''); var var01 = 1; function foo () {document. write (var01); var var01 = 1;} foo (); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
No. 2
<Script language = "javascript"> var00 = 0; document. write (var00 + ''); var01 = 1; function foo () {document. write (var01); var01 = 1;} foo (); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
No. 3
<Script language = "javascript"> var00 = 0; document. write (var00 + ''); var01 = 1; function foo () {document. write (var01); var var01 = 1;} foo (); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
The execution results of these three examples are:
The Code is as follows:
Results # region Results
No.1
0
Undefined
No. 2
0
1
No. 3
0
Undefined
# Endregion
Originally, JavaScript variables also have scopes, but they are very general and divided into global variables and function variables. In the second example, we get 0 and 1 because all the variables are global variables, and the statement block defines two variables in total. The global variables outside the first and third functions do show that the var keyword is irrelevant. The var keyword in the function is critical. It indicates that the second var01 is a variable in the function. Therefore, before initializing var01, the output is 'undefined.
Does the global var01 block in the function? We know that in C/C ++, we can use: to access global variables. Can JavaScript be used? Here, we only need to understand what global variables are. The original global variables are all attributes dynamically added to the Window object instance window, so we only need to use: document. write (window. var01); you can get its value 1. In this context, this in the function is also the window instance to which it points. We can also write the reference as this. var01.
By the way, when looking at the JScript tutorial, it says the variable can only be in the format of [a-zA-Z _] + [a-zA-Z0-9, however, '$' can also be used as a variable name character and can also be used at the beginning, for example, $1234, or even $ is also a valid variable name, faint.