“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
- Page creation creates the GO Global Object
- The first script file loads
- After the script is loaded, check whether the syntax is valid.
- 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:
- The first console.log(a), no doubt prints the values we analyzed above
function a() {}
- The second console.log(a) is printed because the previous assignment to variable A was 123
123
- The third console.log(c), prints out
function c() {}
- The fourth console.log(d), because the condition is false, will not be assigned, and prints
undefined
- The fifth console.log(b), prints out
undefined
- Sixth console.log(b), the previous line assigned a function to variable b, so print
function() {}
- The seventh console.log(c), prints
function 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
- Creating an AO Object
- Look first for parameter and variable declarations, then for function declarations
- Parameters and arguments are unified
- Finding the function declaration overrides the variable declaration