- 2020-03-30 02:34:54
1. Code block
JS is compiled and executed as blocks of code, independent of each other, but with variables and methods Shared. What does that mean? Here's an example:
Above the code in the code block 1 run error, but does not affect the execution of the code block 2, this is the independence of the code block, and the code block 2 can call to the code in the variable, is the block sharing.
2. Declarative function and assignment function
There are two types of function definitions in JS: declarative functions and assignment functions.
The difference between declarative and assignment functions is that at pre-compile time, the declarative functions will be extracted before the JS code is executed in sequence.
3. Pre-compilation period and execution period
In fact, the parsing process of JS is divided into two stages: the pre-compilation (pre-processing) period and the execution period.
At precompile time, JS handles all declared variables and functions in this code block (similar to C compilation), but it is important to note that only declarative functions are processed, and variables are declared but not initialized or assigned.
After understanding the above terms, I believe that you have a general impression of the running mechanism of JS, now let's look at an example:
Why does the browser report an error running the above code? The declaration function will be processed in the preprocessing period, why can't I find the Fn() function? This is actually a understanding was delayed, we stated above the JS engine is executed in the order code block to actually complete said should be carried out in accordance with the code block to pretreatment and execution, that is to say, preprocessing is performed to the block of code statement functions and variables, and for has not been loaded block of code is can't preprocessing, which is compiled while processing core.
Now, let's summarize:
step 1. Read in the first block of code. step 2. Do the syntax analysis, if there is an error, the syntax error (such as the brackets do not match), and jump to step5 . step 3. right var Variables and function Definition to do "precompile processing" (never error reporting because only the correct declarations are parsed). step 4. Execute the code snippet and report an error (such as an undefined variable). step 5. If there is another code snippet, read in the next code snippet and repeat step2 . step6. The end.
Depending on the order in which the HTML document stream is executed, the js code that needs to be executed before the page elements are rendered should be placed in < Body> The previous < Script> Block of code, but js should be placed after page elements are loaded. / body> After the element, the onload event of the body tag is executed at the end.