JavaScript is a weak type of language relative to other languages, in other such as the Java language, the execution of a program requires a compile phase, while in JavaScript there is a similar "precompilation phase" (JavaScript is precompiled in a block of code < Script></script>, that is, each encounter a code block will be precompiled > execution), understand the JavaScript engine execution mechanism, will help write JS code in the process of thinking summary
First, there are two types of declarative methods in JavaScript, Var and function, which declare variables, and the latter declare methods.
In precompilation, JavaScript has two kinds of processing options for both declarations
<script>
var a = "1"; Declaring variable a
function B () {//declaring method B
alert ();
var c = function () {//Declaration variable C
alert ();
}
The above code block, a, c for the variable assignment, b for the function declaration, when executing the above code, first will go into the precompilation phase, to and variable assignment A, C will be in memory to open up a memory space and point to variable name, and assigned to undefined
For a function declaration, the memory space is also opened, but the assigned object assigns the declared function to the functions name
Pre-compile phase: PS: In the order of declaring variables and declaring functions in the code, the variables are declared in the precompilation phase, then the function is declared.
<script>
var a = undefined;
var c = undefined; var B = function () {
alert ();
Implementation phase:
<script>
A = "1";
c = function () {
alert ();
}
Overall execution steps:
<script>
var a = undefined;
var c = undefined;
var B = function () {
alert ();
}
A = "1";
c = function () {
alert ();
}
Topic:
<script>
var a = "1";
Function B () {
alert (a);
var a = "2";
}
B ();
Pre-compilation of Ps:javascript
First, predefined variables, and then predefined functions
Second, the precompilation of the variable is only declared, not initialized, the initialization at the time of execution
Functions defined by Function statements not only declare functions names, but also function bodies are processed
Four, anonymous functions do not precompile
function f () { //Declaration functions F return
1;} alert (f ()); Returns 1
var f = function () { //define anonymous function f return
2;} alert (f ());
The variable f is predefined, then the function f () of the same name overrides the variable F, so the first output is 1; the precompilation of the variable
var f = function () { //define anonymous function f return
1;}
Alert (f ()); Returns the 1
function f () { //Declaration functions F return
2;}
Alert (f ());
The variable f is predefined, then the function f () of the same name overrides the variable F.