There are many differences between javascript and other languages. Pre-compilation is one of them. If you dig into it, you will find many surprises, and you will understand what puzzles you.
Javascript code is executed in segments, with the script as the boundary. The code is pre-compiled before the javascript code segment is executed. During the pre-compilation process, the engine will declare the variables in the scope and initialize them as undefined. parse the defined functions [note the differences with anonymous functions ].
Example
Example 1
- Mm = 2;
- Alert (mm); 2 is displayed.
- Var mm = 2;
- Alert (mm); 2 is displayed.
Everyone here understands that I will not talk about it more.
Example 2
- Alert (mm );
- Mm = 2; error message, mm undefined
My personal understanding is the stage in which the engine pre-compiles the code globally. The global variables that are not declared by var are interpreted as attributes of the above-level object. Here I call it a virtual object, so there will be an undefined prompt
Example 3
- Alert (mm );
- Var mm = 2; the undefined dialog box is displayed.
When the engine pre-compiles the code segment, it defines the variable as undefined; When alert is executed, mm has not assigned a value, so undefined will pop up.
The following code follows the same principle as above.
- Var mm = 2;
- (Function test ()
- {
- Alert (mm );
- Var mm = 3;
- }) () The undefined dialog box is displayed.
Example 4
Declare a defined function [not an anonymous function]
- Test ()
- Function test ()
- {
- Var mm = 2;
- Alert (mm );
- } Pop-up 2
The engine will parse the defined function. Before the test execution, the test function has been parsed, SO 2 will pop up.
Example 5
- Test ()
- Var test = function ()
- {
- Var mm = 3;
- Alert (mm );
- } The system prompts that an object is missing.
At this time, the anonymous function is assigned to a variable, and the engine defines the variable as undefined when parsing the variable. On the other hand, the function is also an object. when the test is executed, the test function is not parsed, so an error message is displayed, indicating that the object is missing.
Summary: The Code in javascript is executed in segments. The engine will pre-compile the code, define the variables in the scope as undefined, and parse the defined functions. Anonymous functions will not be parsed, so we will not say more about the reasons.