scope
Scope is the area of a program's source code where variables are defined. A scope specifies how to find a variable, that is, determine what access the currently executing code has to the variable. JavaScript uses lexical scoping, also known as static scoping. To learn more about scopes, I recommend reading chapter 1 (or Part 1) of JavaScript you Don't Know, which explains scopes from a compilation perspective. In a nutshell, a scope is a well-designed set of rules for storing variables and making them easy to find later.Copy the code
Lexical scope
A lexical scope is defined at the lexical stage of a definition. In other words, the lexical scope is determined by where you write the variable and block scopes when you write the code, so the lexical analyzer keeps the scope the same when it processes the code (most of the time).
Rules for lexical scope in JS:
- The function allows access to data outside the function
- Only functions in the entire code structure can be scoped
- Action rules are first analyzed using lifting rules
- If there is a name in the current scope, external names are not considered
Case 1
var a = 2;
function foo() {
var a = 3;
console.log(a); / / 3
}
foo();
Copy the code
Case 2
function foo() {
console.log(a); / / 2
}
function bar() {
var a = 3;
foo();
}
var a = 2;
bar();
Copy the code
The scope chain
Only functions can make scoped structures, so as long as code has at least one scope, the global scope.
Whenever code has a function, that function constitutes another scope. If there are functions within a function, then a scope can be created within that scope. Listing all such scopes can have a structure: a chain structure within the function pointing out of the function.
Take example 2 above:
function foo() {
console.log(a); / / 2
}
function bar() {
var a = 3;
foo();
}
var a = 2;
bar();
Copy the code
- The global scope has three identifiers: foo, bar, and a
- The scope created by bar, with one identifier: a
Scope is determined by where the code is written and is included level by level.
Let’s use a chain to represent the above code block:
So no matter where a function is called, and no matter how it is called, its lexical scope is determined only by where the function is declared.
practice
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f();
}
checkscope();
Copy the code