In上一篇关于作用域的文章We talk about scope through the call stack.
Whenever we call a function, we create an execution context for that function in the call stack. So far we know that there is a variable environment for storing variables declared through var, and a lexical environment. The lexical environment, in turn, is a stack that places the variables in the function declared through let and const in different levels of block-level scope **.
Based on the above variable environment and lexical environment, we can understand how to find the correct variable in the execution context of a function.
What if the variable we need is not actually in the current execution context, but in the execution context at the previous level? How do we determine which execution context is at the previous level?
This question touches on our topic today: scope chains.
Understanding scope chain is the basis for understanding closures, which are almost ubiquitous in JavaScript. At the same time, scope and scope chain are the foundation of all programming languages. Therefore, if you want to learn a language thoroughly, scope and scope chain must be inseparable.