day19 precompile

1. JS runs trilogy

1. Syntax analysis
2. Precompilation
3. Interpretation and execution

2. Precompiled Prelude

First remember two sentences:
1. Overall promotion of function declarations

test();   
function test() {       
     console.log(a); --> 10    
 }

2. Variable declaration promotion

console.log(a); --> undefined
var a = 10;
console.log(a); --> 10

1. Imply global implies global variables: any variable that is not declared, owned by window

a = 10; --> window.a = 10;

function test(){
	var a = b = 123;--> window.b
}
test();

2. All declared global variables belong to the window

var b = 11; --> window.b = 11;
console.log(b) --> window.b

As follows, the declared local variables are not owned by window.

function test() {
	var b = 123;
}
test();
console.log(window.b); --> undefined

Precompilation happens just before the function is executed:
1. Create AO object (Activation Object)
2. Find formal parameters and variable declarations, use the names of variables and formal parameters as the property names of AO, undefined
3. Actual parameters and formal parameters Unity
4. Find the function declaration, the function name is used as the attribute name, and the value is assigned to the entire function body.

function fn ( a ) {
	console.log(a);
	var a = 123;
	console.log(a );
	function a ( ) { }
	console.log ( a );
	var b = function (){ }
	console.log ( b );
	function d ( ){}
}
fn(1);

When the program is running, when fn(1) is read, the function is executed and precompiled at the moment before execution.

AO{
	a : undefined --> 1 --> function a (){} --> 123,
	b : undefined -->  function(){},
	d : 	function d ( ){}
}

Global pre-compilation:
1. Create a GO object (Global Object, GO === window)
2. Find the function declaration, the function name is used as the attribute name, and the value is assigned to the entire function body. `

//全局预编译生成  GO{ b : 123}
function test(){
      var a = b = 123;--> window.b
}
// 函数执行前预编译AO{ a : undefined}
test();   

//GO{ 
	gloabl : undefined  --> 100,
	fn : function fn(){...}
   }
   
    var global = 100;
    function fn(){
    	console.log(gloabl);
    }
    
 //AO{   '找GO 的gloabl '  }
     fn();

Exercise
1.

function test(){
    console.log(b);//undefined
    if(a){
      var b = 100;
    }
   console.log(b);//undefined
   c = 234;
   console.log(c);//234
}
var a;
test();
a = 10;
console.log(c);//234

Precompile process:

 GO{
     a:undefined --> 10,
     text:function test(){...}
     c:234;
    }
 AO{
     b: undefined;
 }

2、

console.log(test); //function test(){...}
function test(test){
        console.log(test);//function test(){ }
        var test = 234;
        console.log(test);//234
        function test(test){
        }
}
test(1);
var test = 123;
console.log(test);//123