As a rookie of me, learning a little bit of the feeling is still good. Today in the process of learning closure to see the scope and scope chain of the two concepts, I think as a pursuit of the small white, it is necessary to learn more about the next.
Scope of the variable
As far as the JS variable is concerned, there are global variables and local variables. Here I think this is literally understood ..... Here's an example.
var message = "Steamed pork ribs with glutinous rice I made today";//define a global variable functiondoL() { var ss = " The knight is good-looking "; Defines a local variable alert (message); Output "Today I made glutinous rice steamed ribs", in the function can refer to the global variable function alertdo () {alert (ss); } alertdo (); The output "Knight line is very nice", which involves the scope of the variable}; DoL (); Alertdo (); Unable to output alertdo is not definedalert (message); Can output "steamed pork ribs with glutinous rice I made today"
There are 2 interesting places here.
1. When a variable is not declared with Var, we actually declare a global variable, OK, this is wrong, look below, num is a global variable,
and mum = 1;
is actually an attribute assignment operation. First, it tries to chain in the current scope (as declared in the method, then the current scope chain represents the global scope and the method local scope etc ... ) resolves mum ; if mum is found in any current scope chain, the mum property assignment, if mum is not found, it will be in the global object (that is, the topmost object of the current scope chain). such as Window object) to create mum property and assign a value.
Attention! Instead of declaring a global variable, it creates a property of a global object. Since the variable declaration comes with a non-deleted attribute, the comparison of var num = 1 with num = 1, which is a variable declaration with a non-deleted attribute and cannot be deleted, is a property of the global variable and can therefore be removed from the global variable.
var num =1= 1;
2. The variable declaration is advanced to the top of the function, but it has been encountered before.
var scope= "Global"; function T () { console.log (scope); var scope= "Local" Console.log (scope); } T ();
It first outputs the undefined, then the scope, which declares the variables ahead of time and overrides the local variables, which is equivalent to the following
var scope= "Global"; function T () { var scope; Console.log (scope); Scope= "local" Console.log (scope); } T ();
JS Learning--Variable scope