Analyze the

Js code is executed line by line, but before execution, it also has a preparation phase

  • The scope of js is static. It determines the scope of a function when it is defined.
  • When we execute a function, the execution-time context EC is generated
  • Context is divided into global context, and function context. There’s a variable object, scope chain, this points to
  • There are two phases of the execution context cycle, the creation phase (precompilation, that is, variable promotion) and the code-pointing phase

So that makes sense. Variable promotion is just a bunch of pre-compiled operations

So what are the steps for precompiling? What are the steps for precompiling a function?

  • Create AO object AO{}
  • Look for parameter and variable declarations and treat them as AO properties with undefined
  • Arguments and parameters are unified
  • Find the function declaration inside the function body, and assign the function body
 function fn(a, c) {
        console.log(a); // function a(){}
        var a = 555
        console.log(a) / / 555
        console.log(c) // function c (){}
        function a() {}console.log(b) // undefined
        console.log(d) // undefined
        if (false) {
            var d = 1
        }
        var b = function () {}console.log(b) // function (){}
        function c() {}console.log(c) // function c (){}
    }
    fn(1.2)
    // AO: {
    // a: undefined // 1 |function a
    // c: undefined // 2 | function c
    // d: undefined
    // b: undefined
    // }
Copy the code

Some questions about let and VAR


console.log(x) // undefined
var x = 1

Copy the code
  • The var declaration will “create a variable and initialize it to undefined” before the code executes. This explains why console.log(x) gets undefined before var x = 1.

,


console.log(x) / / an error
let x = 1

Copy the code
  • X is not initialized at the time of log execution, so it cannot be used (temporary dead zone)
  • The “creation” process of the LET has been improved, but initialization has not.
  • Var “creation” and “initialization” have been improved.
  • Function ‘create’, ‘initialize’ and ‘assign’ have all been improved