This article is a reference elevation (JavaScript advanced programming) with some personal understanding and summary, using simple small examples and some code snippets to explain the scope and scope chain as much as possible. (This article applies to some JS based friends to refer to)
Execution environment and function definition and execution
The execution environment defines a variable or function that has permission to access other data. In JavaScript, there is an outermost global execution environment, which in a Web browser is generally considered to be the object of window.
Use a small example to explain what is going on in defining functions and executing functions.
From this picture, we can see that when we define a function test1,
1, first create a function object in the heap memory, then the address exists in the test1;
2. An object is created automatically, and the object has a constructor property pointing to the function itself, and finally the prototype property of the function object points to the object;
3, including the global object, the active object created during function execution (explained later) exists on the function's own internal properties [[Scope]].
When a function (test1) is executed,
1, first will create an execution environment ECS and the corresponding scope chain;
2. Then use the values of the arguments and function arguments (if any) to initialize the function's active object (the active object), which is referred to above;
Where the function corresponds to the scope chain is by taking out [[Scope]] value and pushing the active object of the current function into the top level of the scope chain.
We have simply described the function definition and execution, which helps us understand the scope chain and the closures in my blog and how to interpret the special behavior of let in the For loop.
JavaScript Scope and scope chain