JavaScript's scope, the scope chain and pre-parsed

Variables include: global variables, local variables

 

In JAvaScript, the variable is a function of local variables defined in the

 

Scope: is the use of a range of variables,

 

Divided into: the local scope and global scope

 

js --- No variable block-level scope defined a pair of brackets, this variable can be used outside the braces

 

Scope chain: variable is used, from the inside outward, layers of the search, the search can be used directly

 

var num = 10; // scope chain level: 0

   was num2 = 20;

   var str = "abc"

   function f1() {

     was num2 = 20;

     function f2() {

       was num3 = 30;

       console.log(num);

     }

     f2();

   }

   f1 ();

 Layers of search, the search scope to 0 when or if this variable is not found, the result is an error

 

Pre-analysis: that is, before the browser parsing code, the function of variable declarations and statements in advance (lift) to the top of the scope

 

Lift (1) variables

 

Below this case, the variable is declared in advance, but did not advance the value of num, the result is undefined

 

// variable lift

    console.log(num);

    var num = 100;

 

 

After // promoted to:

var num; // variables declared in advance

console.log(num);

    var num = 100;

 (2)

 

Function declaration is advanced, the code can still perform

 

// function declaration is ahead

    f1 ();

    function f1() {

      console.log ( "This function, carried out");

    }

But for the following scenario, the code error

 

f2();

    var f2=function () {

        console.log ( "Xiao Yang Shuaio good");

    }

 

// statement issued after the advance:

var f2; // a variable, undefind

f2 (); // undefind parentheses is not recognized, so the error

    var f2=function () {

        console.log ( "Xiao Yang Shuaio good");

    }

 To not being given, the code can be changed to:

 

where f 2;

    f2=function () {

      console.log ( "Xiao Yang Shuaio good");

    };

    f2();

Guess you like

Origin www.cnblogs.com/tongguilin/p/12229553.html