“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”

1. Title Description

The following code outputs the order

var a = 1;
console.log(a);
function fn(a, c){
    console.log(a);
    var a = 123;
    console.log(a);
    console.log(c);
    
    function a(){};
    if(false) {
      var d = 999;
    }
    console.log(d);
    console.log(b);
    
    var b = function(){};
    console.log(b);
    
    function c(){};
    console.log(c)
 }
 var c = function (){
  console.log("I at C function");
 }
 console.log(c);
 fn(1.2);
Copy the code

Second, the analysis

  1. Page creation creates the GO Global Object
  2. The first script file loads
  3. After the script is loaded, check whether the syntax is valid.
  4. Start precompiling, look for variable declarations, as GO property, value assigned to undefined; Find the function declaration, as the GO attribute, with the value assigned to the function body;
GO/window = {a: undefined, c: undefined, fun: function(a, c) {... }}Copy the code

Interpret the execution code (until the call function fn(1, 2) statement is executed), and each attribute is assigned a value

// Abstract description
GO/window = {
    a: 1.c: function (){
        console.log("I at C function");
    }
    fn: function(a) {... }}Copy the code

So it prints out before fn executes

1
function c() {}
Copy the code

A function precompilation also takes place before fn is executed to create the AO Active Object.

// First find the parameter and variable declarations and assign undefined
AO = {
 a: undefined.c: undefined.d: undefined.b: undefined
}
// Assign the argument to the parameter
AO = {
 a: 1.c: 2.d: undefined.b: undefined
}
// Look for the function declaration, which overrides the variable declaration
AO = {
 a: function a() {},
 c: function c() {},
 d: undefined.b: undefined
}
Copy the code

Then start explaining the execution:

  1. The first console.log(a), no doubt prints the values we analyzed abovefunction a() {}
  2. The second console.log(a) is printed because the previous assignment to variable A was 123123
  3. The third console.log(c), prints outfunction c() {}
  4. The fourth console.log(d), because the condition is false, will not be assigned, and printsundefined
  5. The fifth console.log(b), prints outundefined
  6. Sixth console.log(b), the previous line assigned a function to variable b, so printfunction() {}
  7. The seventh console.log(c), printsfunction c() {}

In conclusion, we can know

Function c(){} function a(){} 123 function c(){} undefined undefined function (){} function c(){}Copy the code

Third, summary

When analyzing precompile, just follow these steps to analyze, we can find the correct answer

  1. Creating an AO Object
  2. Look first for parameter and variable declarations, then for function declarations
  3. Parameters and arguments are unified
  4. Finding the function declaration overrides the variable declaration