defined in the body of the function are global variables, defined in the body of the function of local variables. The definition here refers to the Var declaration.
JavaScript has an implied global concept, meaning that any variable you don't declare becomes a global object attribute. For example:
Copy Code code as follows:
function Test () {
myname = "huming";
alert (myname);
}
Test (); "Huming"
alert (myname); "Huming"
Two results are the same, stating that myname is a global variable.
So, is there any difference between an implicit global variable and a well-defined global variable? The answer must be yes, look at the following example:
Copy Code code as follows:
Define three global variables
var global_test1 = 1;
Global_test2 = 2; Antithesis
(function () {
GLOBAL_TEST3 = 3; Antithesis
}());
Attempt to delete
Delete Global_test1; False
Delete Global_test2; True
Delete Global_test3; True
Test the deletion
Alert (typeof Global_test1); "Number"
Alert (typeof Global_test2); "Undefined"
Alert (typeof Global_test3); "Undefined"
As can be seen from the example above, the global_test1 defined by Var outside the function cannot be deleted, and Global_test2 and GLOBAL_TEST3, which are not defined by Var, are removed (whether they are created in the function body).
In summary, global variables declared by var outside the function body cannot be deleted, and implicit global variables can be deleted.
Note here: JavaScript has a behavior called "hoisting" (Mount/Top parsing/Pre-resolution).
We illustrate by an example:
Copy Code code as follows:
var myname = "Huming"; Declaring global variables
function Test () {
alert (myname);
var myname = "Local_huming";
alert (myname);
}
Test ();
Do you guess two times alert's content is consistent?? Clearly inconsistent, consistent still used to say? The actual output is: "Undefined", "local_huming".
The above example is equivalent to
Copy Code code as follows:
var myname = "Huming"; Declaring global variables
function Test () {
var myname;
Alert (maname);<br> myname = "local_huming";
alert (myname); "Local"
}
Test ();
The myname of the first alert output is not what you think of as a global variable, but the local variable that is in a scope (a function body). Although it has not yet been declared, it is regarded as a statement. This is the so-called "hoisting".
This should be understood. When you use a variable in the body of a function and then declare it again, you may have an error.
Writing specification:
Copy Code code as follows:
function Test () {
var a = 1,
b = 2,
c = A + B,
D = {},
E
F
function Body ...
}
The advantage is:
1, all local variables are defined at the beginning of the function, easy to find;
2. Prevent variables from using logic errors before they are defined.
Small partners have understood the JavaScript variable statement, the above content is very detailed and easy to understand, the final summary is also very pertinent, small partners do not miss.