1. The scope chain of JavaScript functions is divided into definition-time scope chain and run-time scope chain;
2. When a function is defined, it has an attribute [[scope]] indicating its definition scope chain. The definition scope chain [[scope]] follows the following rules: a function’s definition scope chain [[ scope]] is always the execution scope chain of the external function in which it is located;
3. The definition scope chain of the global function only contains the attributes of window;
4. When a function is executed, the scope chain is always pushed into the current active object at the head of the scope chain when it is defined (it contains this, arguments, parameters, and local variables);
5. When a function is executed, variable addressing is always searched from the top of the scope chain downwards; therefore, the addressing speed of global variables is the slowest;
6. When the internal function is executed, he can still access its complete scope chain. This is why closures can access variables defined by completed external functions at runtime;
7. When a with statement is encountered during function execution, all attributes of the object specified with will be temporarily pushed into the top of the scope chain as the top of the scope chain;
8. When function execution encounters a catch, the error object specified by catch will be temporarily pushed into the top of the scope chain as the top of the scope chain;
Let's give an example and draw the scope chain to deepen understanding:
There is such a piece of code:
Copy the code code as follows:
function assignEvents(){
var id = "xdi9592";
document.getElementById("save-btn").onclick = function(event){
saveDocument(id);
};
}
Call the anonymous closure generated by this function Closure, and draw the following figure to show the scope chain when assignEvent is executed and the scope chain when Closure is defined: