In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail the relevant knowledge about the promotion of javascript variables, which the editor thinks is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Let's look at the code first. What do you think is the output of the following code?
ShowName () console.log (myname) var myname = 'geek time' function showName () {console.log ('function showName is executed');}
Programmers who have used JavaScript development should know that JavaScript is executed sequentially. If you follow this logic, then:
When you get to line 1, execution should report an error because the function showName has not yet been defined
Similarly, when line 2 is executed, an error will also be reported because the variable myname is not defined.
However, the actual implementation result is not so, as shown in the following figure:
Line 1 output "function showName is executed", line 2 output "undefined", which is a little different from the previous imagination of the sequence of execution ah!
From the above execution results, you should already know that functions or variables can be used before definition, so can JavaScript code continue to execute if you use undefined variables or functions? To verify this, we can delete the definition of the variable myname on line 3, as follows:
ShowName () console.log (myname) function showName () {console.log ('function showName is executed');}
Then when the code is executed again, the JavaScript engine reports an error with the following result:
Judging from the execution results of the above two pieces of code, we can draw the following three conclusions:
During execution, JavaScript execution will report an error if undeclared variables are used.
There is no error in using a variable before it is defined, but the value of the variable will be undefined, not what it was when it was defined.
Using a function before it is defined is error-free and the function executes correctly.
The first conclusion is easy to understand, because the variable is not defined, so the variable cannot be found when the JavaScript code is executed, so JavaScript throws an error.
But for the second and third conclusions, it is quite puzzling:
Why can variables and functions be used before they are defined? This seems to indicate that the JavaScript code is not executed line by line.
In the same way, why are variables and functions handled differently? For example, in the execution result above, the showName function used in advance can print out the full result, but the value of the myname variable used in advance is undefined, not the geek time value used in the definition.
Variable promotion (Hoisting)
To explain these two problems, you need to understand what variable ascension is.
But before we introduce variable promotion, let's take a look at what declarations and assignments are in JavaScript through the following code.
Var myname = 'geek time'
You can think of this code as two lines of code:
Var myname / / declaration part myname = 'geek time' / / assignment part
As shown in the following figure:
The above is the declaration and assignment of variables, so let's take a look at the declaration and assignment of functions, combined with the following code:
Function foo () {console.log ('foo')} var bar = function () {console.log (' bar')}
The first function, foo, is a complete function declaration, that is, no assignment is involved; the second function is to declare the variable bar and then assign function () {console.log ('bar')} to bar. For intuitive understanding, you can refer to the following figure:
Well, now that we understand the declaration and assignment operations, we can talk about what variable promotion is.
The so-called variable promotion refers to the "behavior" that the JavaScript engine promotes the declaration part of the variable and the declaration part of the function to the beginning of the code during the execution of JavaScript code. After the variable is promoted, the variable is set to a default value, which is the familiar undefined.
Let's simulate the implementation:
/ * * variable promotion part * / / raise the variable myname to the beginning, / / at the same time assign the value undefinedvar myname = undefined// to the function showName to the beginning function showName () {console.log ('showName called');} / * * executable code part * / showName () console.log (myname) / / remove the var declaration part and retain the assignment statement myname = 'geek time'
In order to simulate the effect of variable improvement, we made the following adjustments to the code, as shown in the following figure:
As you can see from the figure, there are two main adjustments to the original code:
The first is to promote the declared parts to the beginning of the code, such as the variable myname and the function showName, and set the default value undefined for the variable.
The second is to remove the originally declared variables and functions, such as the statement var myname = 'geek time', remove the var declaration, and remove the function declaration of showName as a whole.
Through these two steps, the effect of variable improvement can be achieved. You can also execute this code that simulates variable promotion, and the output should be exactly the same as the first piece of code.
By improving the code with this simulated variable, I believe you already understand why you can use variables or functions before definition-functions and variables are promoted to the beginning of the code before execution.
The execution flow of JavaScript code
In the literal sense of the concept, "variable promotion" means that the declaration of variables and functions moves to the front of the code at the physical level, as we simulated. However, this is not accurate. In fact, the position of variables and function declarations in the code does not change, and is put into memory by the JavaScript engine during the compilation phase. Yes, you heard right. A piece of JavaScript code needs to be compiled by the JavaScript engine before it can be executed. After the compilation is completed, it will enter the execution phase. You can refer to the following figure for an overview of the process:
1. Compilation phase
So what is the relationship between the compilation phase and variable promotion?
To figure this out, let's go back to the above code that simulates variable enhancement, which can be divided into two parts for ease of introduction.
The first part: the code of variable promotion part.
Var myname = undefinedfunction showName () {console.log ('function showName is executed');}
The second part: the code of the execution part.
ShowName () console.log (myname) myname = 'geek time'
Below, we can refine the execution process of JavaScript, as shown in the following figure:
As you can see from the figure above, entering a piece of code, after compilation, produces two parts: the execution context (Execution context) and the executable code.
Execution context is the environment in which JavaScript executes a piece of code. For example, when a function is called, it enters the execution context of the function and determines the this, variables, objects and functions used by the function during execution.
For details on the execution context, I will write in the next article "08 | call Stack: why does JavaScript code have stack overflows? "for details, now you just need to know that there is a variable environment object (Viriable Environment) in the execution context, which stores the variable promotion content, such as the variable myname and the function showName in the above code, are stored in this object.
You can simply think of the variable environment object as the following structure:
VariableEnvironment: myname-> undefined, showName-> function: {console.log (myname)
After understanding the structure of the variable environment object, let's combine the following code to analyze how the variable environment object is generated.
ShowName () console.log (myname) var myname = 'geek time' function showName () {console.log ('function showName is executed');}
We can analyze the above code one by one:
Lines 1 and 2, because these two lines of code are not declared operations, the JavaScript engine will not do any processing
Line 3, because this line is declared by var, the JavaScript engine will create a property called myname in the environment object and initialize it with undefined
In line 4, the JavaScript engine finds a function defined by function, so it stores the function definition in the HEAP, creates a property of showName in the environment object, and points that property value to the location of the function in the heap. (it doesn't matter if you don't know about the heap. I'll cover JavaScript's execution stack and execution stack in a later article).
This generates the variable environment object. Next, the JavaScript engine compiles the code other than the declaration into bytecode. As for the details of the bytecode, I will explain it in detail in a later article. You can compare the simulation code as follows:
ShowName () console.log (myname) myname = 'geek time'
Well, now that you have the execution context and executable code, it's time for the execution phase.
two。 Execution phase
The JavaScript engine starts executing "executable code", one line at a time in order. Let's analyze the execution process one by one:
When the showName function is executed, the JavaScript engine starts looking for the function in the variable environment object, and because there is a reference to the function in the variable environment object, the JavaScript engine starts executing the function and outputs the result of "function showName is executed".
Next, print the "myname" information, and the JavaScript engine continues to look for the object in the variable environment object, and because the variable environment has a myname variable and its value is undefined, it outputs undefined.
Next, execute line 3 to assign the geek time to the myname variable. After the assignment, the value of the myname property in the variable environment is changed to the geek time, as shown below:
VariableEnvironment: myname-> geek time, showName-> function: {console.log (myname)
All right, this is the process of compiling and executing a piece of code.
What if the same variable or function appears in the code?
Now that you know that before executing a piece of JavaScript code, the code is compiled and the functions and variables in the code are saved to the variable environment of the execution context, so what will the JavaScript engine do if there is a function or variable with the same name in the code?
Let's take a look at the following code:
Function showName () {console.log ('geek state');} showName (); function showName () {console.log ('geek time');} showName ()
In the above code, we first define a function of showName, which prints out "geek state"; then calls showName and defines a showName function that prints out "geek time"; finally, we continue to call showName. So can you analyze what the values printed out by these two calls are?
Let's analyze the complete implementation process:
The first is the compilation phase. When the first showName function is encountered, the function body is stored in the variable environment. Next comes the second showName function, which continues to be stored in the variable environment, but there is already a showName function in the variable environment, and at this point, the second showName function overrides the first showName function. This leaves only the second showName function in the variable environment.
Next comes the execution phase. Execute the first showName function first, but because you are looking for the showName function from the variable environment, and only the second showName function is saved in the variable environment, the second function is finally called, and the print is "geek time". The second execution of the showName function follows the same process, so the output is also "geek time".
To sum up, if a piece of code defines two functions with the same name, it is the last function that will eventually take effect.
This is the end of this article on "what is the knowledge related to the promotion of javascript variables?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.