An eight point summary of the Javascript scope chain

  • 2020-03-30 00:48:05
  • OfStack

1. The scope chain of JavaScript functions is divided into definition scope chain and runtime scope chain;

2. When a function is defined, it has a property [[scope]] indicating its definition scope chain. The definition scope chain [[scope]] follows the rule that the definition scope chain [[scope]] of a function is always the execution scope chain of the external function it is in.

3. The scope chain of global function definition only contains the properties of window;

4. The scope chain of a function is always pressed into the current active object at the head of the scope chain at the time of definition (it contains this,arguments, parameters, local variables);

5. When the function is executed, the variable addressing is always found from the top of the scope chain down; So global variables have the slowest addressing speed;

6. When an inner function is executed, it still has access to its full scope chain. This is why closures are able to access variables defined by finished external functions at run time;

7. When the execution of the function encounters the with statement, it will temporarily press in all the attributes of the object specified with at the top of the scope chain as the top of the scope chain;

8. When the function execution encounters catch, it will temporarily press the error object specified by catch into the top of the scope chain as the top of the scope chain;

Here's an example and draw a scope chain to help you understand:

Here's a piece of code:


function assignEvents(){
    var id = "xdi9592";
    document.getElementById("save-btn").onclick = function(event){
        saveDocument(id);
    };
}

If the anonymous Closure generated by this function is called a Closure, the following figure is drawn as the scope chain when the assignEvent is executed and the scope chain when the Closure is defined:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201312/20131206094906.png ">

Related articles: