"Execution environment", when you hear this term, you may become very confused! And it is also called "execution context" in many literatures, but it is actually the same thing. Books and materials often explain it very complicatedly. This is a difficult part to understand in JS. Don’t worry, this article tries to explain this concept in simple and easy language.
Let’s look at an example first:
We enter in the browser console:
var a=1;console.log(window.a);console.log(a);
The result is output 1, obviously A variable is a property of the window object.
Then let me ask you: What is the execution environment of variable a?
I believe it is not difficult for you to answer: It is the window object! Indeed, you are right. The window object is the execution environment of variable a. It is called the global execution environment because it is the most peripheral execution environment. Here, a is defined in the global execution environment by default, so a and window.a are the same.
Let’s look at the next example:
function output(){ var a=1; console.log(a); }
In this example, a is defined inside the function, then the execution environment of a is the function execution environment (output).
If you enter:
console.log(a);
in the window, an error will be reported, because a is only visible in the function output.
But if you enter:
console.log(output);
, the function will be displayed normally, because the execution environment of the function output is window, and of course it can be displayed in the window!
We know that the output function is in the window environment. When the program runs the output function, you should have guessed it:
The window environment hands over control to the output function environment, and the output environment becomes the home field.
So, what actually happened behind the scenes?
There is something in JS called the execution environment stack, or execution context stack. I don’t know what the stack is and I should add some data structure.
Like a stack of boxes, the global execution environment is placed at the bottom of the execution environment stack. When running to the output function, the execution environment of this function is also packaged into a box and 'stacked' on top of the global execution environment. If I want to continue running other functions in the global environment, just like getting something from the bottom box, the output function must be executed first. To put it figuratively, it's like taking away the top box before moving the bottom box.
Related recommendations:
How to understand the types, parameters and execution environment in JavaScript
Detailed explanation of execution environment and scope instances
javascript scope chain and execution environment
The above is the detailed content of Introduction to JS execution environment examples. For more information, please follow other related articles on the PHP Chinese website!