To discuss the advance of variable declarations only:
Understand this code:
var name = "AAA"; function Test () { alert (typeof name); var name = "BBB"; Alert (typeof name);} Test ();
-Answer: Undefined, string
Analysis
1, two principles: A, JS in the declaration of variables in advance; B, the scope of JS and the way to search for variables
2, the first time to execute "typeof name", the first will be in the scope of the function to query whether the name exists. Because of the advance of the variable declaration, the declaration of name in the local scope was advanced, but was not assigned a value, so it is undefined.
3, the second time better understanding, is a string.
4, because the name has been found in the local scope, so it does not need to be found in the global scope, so two times the name is considered in the local scope. You can see the description of the scope in the fourth chapter of Advanced JavaScript programming, and focus on the process of JS's search for variables along the scope. As follows:
5, notice that sometimes the browser will have some default operation, this time needs to be specific analysis.
Practice Code
var x = 1; function test2 (x) { alert (x); var x = 2; alert (x);} function test3 () { alert (x); var x = 3; alert (x);} Test2 (x); Test3 ();
-Answer: 1,2;undefined,3;
JS Small tips of variable declaration in advance