- The variable declaration statement of JS is always executed first in its scope, regardless of the location where it is defined;
- Inside the function body, local variables have a higher precedence than global variables with the same name.
- Javas Scope classification
- Variables that are not defined with Var, regardless of where they are defined, are global variables, and the global variables are essentially properties under window
A variable declaration statement of 1 JS is always executed first in its scope, regardless of where it is defined
2 var function ()3 {4 console.log (s);//output is undefined5var s= "You" ; 6 }; 7 test ();
The reason is that in the scope of the test function, although Var s= "You" behind the console, but because the declaration statement of the variable will be executed first, it is equivalent to:
2 var test= function 3 { 4 var s;// 5 Conso Le.log (s); // output is undefined 6 var s= "You" ; 7 }; 8 test ();
Console.log (s) results for undefined;
2 inside the function body, the precedence of the local variable is higher than the global variable with the same name
var s= "Hello"; varfunction() { var s= "You"; Console.log (s); // the output is "you" }; Test ();
The local variable takes precedence, so the print result is "you"
Scope Classification of 3JS
There are only two types of JavaScript scope classifications: Global scope and Method scope
Functions are also called methods, so the scope of a method can be understood as a function within a scope, unlike C or C + + language, JS does not have block-level scope, for (Var i=0; i++) The I scope here is the scope of the function where the for loop is located, not just within the for loop;
4 variables that are not defined with Var, regardless of where they are defined, are global variables
function Test ()// define functions test{ i=100; } Test ()// Execute function testconsole.log (i);//Output 100
Console.log (WINDOW.I);//Output 100
In addition, it is necessary to note that function xxx () {}; Only the definition of a XXX (), and no function code, if there is no test (), then the output of I is undefined, can also be
function xxx () {//code};xxx (); merge written as: (function XXX () { // Code}) ():
The form: (function xxx () {}) () is the function xxx is defined first and executes the function; The advantage of this method is that it can guarantee the variable lifetime, less global variables, and easy to recycle the variables.
About variables in JavaScript