JS advanced – scope, scope chain and pre parsing

Time:2020-5-26

Scope, scope chain and resolver

   
  • Variables – > local and global variables,
  • Scope: the scope of variable usage
 
  1. Local scope and global scope
  2. There is no block level scope in JS — a pair of variables defined in brackets, which can be used outside the braces
  3. Variables defined in a function are local variables
 
    while (true) {
      var num = 10;
      break;
    }
    console.log(num); //10

 

    {
      var num2 = 100;
    }
    console.log(num2); //100

 

    if (true) {
      var num3 = 1000;
    }
    console.log(num3); //1000

 

function f1() {
      //Local variable
      var num = 10;
    }
    console.log (Num); // underfound local variable, not accessible outside

 

Scope chain: the use of variables, from the inside to the outside, layer by layer search, you can directly use the search
Level by level search. When level 0 scope is searched, if this variable is still not found, the result is an error
 
Var num = 10; // scope chain level: 0
    var num2 = 20;
    var str = "abc"
    function f1() {
      var num2 = 20;
      function f2() {
        var num3 = 30;
        console.log(num);
      }
      f2();
    }
    f1(); //10

 

Pre parsing: before the browser parses the code, advance (promote) the declaration of variables and functions to the top of the scope
 
Variable advanced, value not advanced
var =num
console.log(num);
num=10;
 
//Variable promotion
    console.log(num);
    var num = 100; //undefinded

 

//Function declaration is advanced
    f1();
    function f1() {
      console.log ("this function, executed");
    }

 

report errors

f2()
    var f2 = function () {
      console.log ("Xiao Yang is so handsome");
    };