scope
- concept
- The area where a code segment resides, statically, is determined at code writing time
- classification
- Global scope
- Function scope
- Block scope (ES6)
- role
- Isolate variables. Variables of the same name in different scopes do not conflict
The scope chain
- understand
- A chain of scopes of multiple subordinate relationships that are oriented from bottom up (inside out)
- Variables are found along the scope chain
- A lookup rule for finding a variable
- Finds the corresponding attribute in the execution context of the current scope, returns it directly if any, otherwise goes up
- Finds the corresponding attribute in the execution context of the upper scope, returns it directly if there is one, otherwise goes to the upper scope
- The same process is performed until the global scope is found, and if it returns directly, an exception that was not found is thrown
var a = 10
function fn1() {
var b = 20
function fn2() {
var c = 30
console.log('a:' + a) // a:10
console.log('b:' + b) // b:20
console.log('c:' + c) // c:30
}
fn2()
}
fn1()
Copy the code