Several concepts of scope:
1. The functions in JavaScript run in the scope they are defined in, not in the scope in which they are executed.
2, global variables have global scope, the variables declared within the function are defined only within the function body, the scope is local.
3, in the function body, the local variable priority is higher than the global variable.
4, the definition of global variables can not need to declare Var, the definition of local variables must be declared with Var. (usually the recommendation is declared with Var)
The scope is easy to encounter several misunderstandings:
1: Global variable and local variable scope confusion. (Novice misunderstanding)
Fig. 1 Fig. 2
1 and 2, when local variables and global variables are repeated, local variables take precedence over global variables, and the Checkscope () method in Figure 1 re-declares scope with VAR, thus changing and returning a declared local variable scope. There is no re-declaration in Figure 2, so the global variable scope is changed and returned in the Checkscope () method.
2: Ignore the role of variable promotion.
Figure 3
3, the first output is not the ideal "global", but is undefined; this is because local variables are always defined in the function body in JavaScript, and variable declarations in the function body are promoted to the top of the function by default, i.e. Checkscope () The actual order of execution in the method is:
function Checkscope () {
var scope;
Console.log (scope);
Scope = "local";
Console.log (scope);
}
3: Declare global variables with VAR and declare global variables without using var.
JavaScript Scopes (Consolidation)