For students to learn the front end, scope, scope chain, is not strange, almost the first day to learn JS contact. I always feel that I have a very superficial understanding of this noun that hangs around every day. Today, I reviewed my previous study notes and reorganized this concept based on my own understanding.

What is a scope: A scope is an object whose function is storage. Variables in a scope are members of an object.

What is a scope chain: Controls the order in which variables are used, local first, then global.

So the last classic code, what was the output? It’s not hard at all to believe, why is this output, what’s going on inside the function. Here we go.

var  a=10
function fun(){
var a = 100;
a++;
console.log(a);
}
fun()   //101
console.log(a) //10

Copy the code

1. Before executing the program: Create an execution environment stack

Execution environment stack, which holds the execution environment of each called function in turn. The window object is created by pushing the first global execution environment (global EC) into the execution environment stack, and global EC references the Window objectCopy the code

2. Start the program

All global variables are stored in the global scope object Window

3. When defining functions

  • Add function name variables globally
  • Creating a function object
  • Function name variables refer to function objects
  • The function object has a scope property that refers back to the scope at which the function was created

4. When calling a function

  • Push the execution environment of a function into the execution environment stack
  • Create the function active object AO(function scope object, create all the local variables of the function
  • The newly pressed function execution environment refers to the active object AO
  • The parent of the function scope points to the scope where the function was created
  • In this case, fn functions with local variable A, and outputs 101

5. After a function call

  • The function in the execution stack executes the environment out of the stack
  • Causes the function scope object AO to be released
  • Causes local variables to be released together
  • At this point, fn’s local variable A is released, leaving only global a = 10; The output of 10