1. Scope

Scope: The inner environment can access all the outer environments through the scope chain, but the outer environment cannot access any variables and functions in the inner environment. The connections between these environments are linear and orderly. Each environment can search up the scope chain to query variable and function names; But no environment can enter another execution environment by searching down the scope chain.

var color = "blue"; function changeColor(){ var anotherColor = "red"; function swapColors(){ var tempColor = anotherColor; anotherColor = color; color = tempColor; // Here you can access color, anotherColor, and tempColor} // here you can access color and anotherColor, but not tempColor swapColors(); } // Only color changeColor() can be accessed;Copy the code
    1. The above code involves three execution environments: the global environment, the local environment of changeColor(), and the local environment of swapColors(). The global environment has a variable color and a function changeColor(). The local environment of changeColor() has a variable named anotherColor and a function named swapColors(), but it also has access to the variable color in the global environment. The local environment of swapColors() has a variable tempColor that can only be accessed in this environment. Neither the global environment nor the local environment of changeColor() has access to tempColor. However, within swapColors(), all variables in the other two environments are accessible because those environments are its parent execution environments. Figure 4-3 visually shows the scope chain of the previous example.
    1. For swapColors() in this example, there are three objects in the scope chain: The local environment of the swapColors() variable object, the changeColor() variable object, and the global variable object starts by searching for the variable and function names in its own variable object and, if not, the upper scope chain. ChangeColor () ‘s scope chain, execution environment, and scope 75 contain only two objects: its own variable object and its global variable object. That is, it cannot access the environment of swapColors().