In fact, I have read a lot of articles about the scope chain, but I have never been able to make a detailed summary. Today I will combine some of the things I have seen with my own ideas, summarized into the following eight points 1. the scope chain of JavaScript functions can be defined as the scope chain and the runtime scope chain;
2. when a function is defined, it has an attribute [[scope] indicating its definition scope chain. When it is defined, the scope chain [[scope] follows such a rule: when a function is defined, the scope chain [[scope] is always the scope chain for executing the external function;
3. the scope Chain Defined by the global function only contains the properties of window;
4. When a function is executed, the scope chain is always pushed to the current active object in the header of the scope chain when it is defined (it contains this, arguments, parameters, local variables );
5. During function execution, variable addressing always looks down from the top of the scope chain; therefore, the addressing speed of global variables is the slowest;
6. When an internal function is executed, it can still access its complete scope chain. This is why the closure can access the variable defined by the ended external function at runtime;
7. When a with statement is encountered in function execution, all attributes of the objects specified by with are temporarily pushed to the top of the scope chain as the top of the scope chain;
8. When a function execution encounters a catch, it will temporarily press the error object specified by catch at the top of the scope chain as the top of the scope chain;
The following is an example and a scope chain is drawn to deepen understanding:
There is such a piece of code:
The Code is as follows:
Function assignEvents (){
Var id = "xdi9592 ";
Document. getElementById ("save-btn"). onclick = function (event ){
SaveDocument (id );
};
}
When the anonymous Closure generated by this function is called Closure, the scope chain is drawn as the definition of assignEvent and Closure during execution: