defined in the function body is a global variable, defined in the body of the function belongs to the local variable. The definition here refers to the declaration through Var.
JavaScript has an implicit global concept, meaning that any variable you don't declare will become a global object property. For example:
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 is definitely yes, look at the following example:
Define three global variables var global_test1 = 1;global_test2 = 2; Negative (function () {GLOBAL_TEST3 = 3;//negative ());//try to delete global_test1; Falsedelete Global_test2; Truedelete 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 above example, Global_test1 defined by Var outside of a function cannot be deleted, and global_test2 and global_test3 that are not defined by VAR are deleted (whether or not created within the function body).
In summary, global variables declared through Var outside of the function body cannot be deleted, and implicit global variables can be deleted.
Here are some notes: JavaScript has a behavior called "hoisting" (Mount/Sticky parsing/pre-parsing).
We use an example to illustrate:
var myname = "Huming"; Declares the global variable function test () { alert (myname); var myname = "local_huming"; alert (myname);} Test ();
Do you think the content of alert is consistent two times?? It is clear that there is no agreement. The actual output is: "Undefined", "local_huming".
The above example is equivalent to
var myname = "Huming"; Declares the global variable function test () {var myname; alert (maname);
myname = "local_huming"; alert (myname);//"Local"}test ();
The myname of the first alert output is not a global variable you think of, but a local variable within a scope (a function body). Although it has not yet been declared, it is deemed to be a statement. This is called the "hoisting".
This should be understood. When you use a variable in the body of a function and then re-declare it later, you can create an error.
Writing specification:
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.
The declaration of a JavaScript variable