Don't say a word; first a piece of code;
var scope= ' global ';
function Test () {
alert (scope); Output undefine, not global
var scope= ' local ';
alert (scope); Output Local
}
Test ();
You may think that the first alert will output global;
But in fact the first alert output is undefined;
What's going on here?
To explore this problem first of all to explain the next two concepts;
1: Function Scope:
function scope refers to the variables declared within the function are only valid within this function;
2: Declaration in advance:
Declaration in advance means that a variable declared anywhere within a function will be first parsed at the top of the function;
After understanding the concept of declaration in advance, the above code is equivalent to the following;
If this statement is not literally understood in advance, then it is easy to understand from the code;
var scope= ' global ';
function Test () {
var scope; This variable is declared first.
alert (scope); Because it is not yet assigned; so it's undefine.
Scope= ' local '; Assign value
alert (scope); Output Local
}
Test ();
So the experience is that in the function body first the variables to be used are declared at the beginning of the function;
Instead of declaring variables when they are used;
As to why the first alert is not an output global;
Because the local variables in the function body will obscure the global variables;
Must not explain too much;
JavaScript's function scope and declaration in advance