JavaScript is a weak type of language relative to other languages, and in other applications such as the Java language, the execution of the program requires a compile stage, and in JavaScript there is a similar "precompilation phase" (JavaScript precompilation is scoped to a block of code < Script></script>, that is, each time a block of code will be precompiled > executed), understand the JavaScript engine execution mechanism, will help in the process of writing JS code summary of Ideas
First, in the popular science of JavaScript in two ways of declaring, Var and function, the former declares a variable, the latter is a method of declaring
In precompilation, JavaScript makes two kinds of processing schemes for both declarations.
123456789 |
<SCRIPT> var a = "1" ; //declaration variable a &NBSP; function b () { //declaring method B &NBSP;&NBSP; alert (); " var c = function () { //declaring variable C alert (); </SCRIPT> |
In the above code block, a, c is a variable assignment, B is a function declaration, when executing the above code, the first step into the pre-compilation phase, the assignment of a to the variable A, C will open a memory space in memory and point to the variable name, and assigned to a value of undefined
For function declarations, memory space is also created, but assigned objects assign values to function names
precompilation phase: (PS: Variables are declared and functions are declared in the precompilation phase, regardless of the order in which the variables are declared and declared in the code)
12345 |
<script> var a = undefined; var c = undefined; var b = function (){ alert(); } </script> |
Implementation phase:
123456 |
<script> a = "1" ; c = function (){ alert(); } </script> |
Overall implementation steps:
123456789101112 |
<script> var a = undefined; var c = undefined; var b = function () { alert (); " a = " 1 " ; C = function () { alert (); </SCRIPT> |
Topic:
12345678 |
<script> var a = "1" ; function b(){ alert(a); var a = "2" ; } b(); </script> |
Pre-compilation of Ps:javascript
First, pre-defined variables, and then pre-defined functions
Second, the pre-compilation of the variable is only declared, not initialized, initialization at execution time
functions defined by the FUNCTION statement not only declare the function name, but also handle the function body.
Iv. anonymous functions are not precompiled
1234 |
function f(){ // 声明函数f return 1; } alert(f()); // 返回1 var f = function (){ // 定义匿名函数f return 2; } alert(f()); // 返回2 |
The variable f is pre-defined, and then the function f () with the same name overrides the variable F, so the first output is 1; the pre-compilation of the variable
123456 |
var f = function (){ // 定义匿名函数f return 1; } alert(f()); // 返回1 function f(){ // 声明函数f return 2; } alert(f()); // 返回1 |
The variable f is pre-defined and then the function f () with the same name overrides the variable F.
Pre-compilation (lexical analysis) and execution phases in JS