How to understand the scope of

  1. JS not block-level scope
  2. Only drink a function of global scope

It is divided into several scopes

  1. Free variable
  2. The scope chain, that is, to find free variables
  3. Closure of two scenes

Free variable

1 var names = 'zhangsan'
2 console.log(names) // zhangsan
3 var num = 100
4 function t(){
5     var num = 200
6     console.log(num) //200
7 }
8 t()

The scope chain, that is, to find free variables

// scope chain (a continuous variable to find parent) 
var SD = 22 is
 function FG () {
     var S2 = 666
     // this variable is not defined scope, i.e., the free variables 
    the console.log (S2) // 666 
    the console.log (SD) // 22 is 
} 
FG () 
var W = 123
 function W1 () {
     var V = 568
     function w2 of () {
         var C = 300
         // no parent will continue looking like 
        console.log (w ) // 123 
        the console.log (V) // 568 
        the console.log (C) // 300
    }
    w2()
}
w1()

Closure of two scenes

1  // closure 
2  // 1 functions as a return value 
3  // 2, a function as an argument 
. 4  
. 5  function SS () {
 . 6      var E = 888
 . 7      return  function () {
 . 8          the console.log (E)   / / 888 // free variables, i.e. ss function will find in his parent scope 
. 9      }
 10  }
 . 11  
12 is  var S1 = ss ()
 13 is  var E = 999
 14  S1 ()
 15  
16  function A1 () {
 . 17      var W 543 =
 18      return function () {
 . 19          the console.log (W)   // 543 // free variables, will find his parent scope i.e. ss function 
20 is      }
 21 is  }
 22 is  var Z = A1 ()
 23 is  function A2 (parm) {
 24      var W = 900
 25      parm ()
 26 is  }
 27 A2 (Z)

 

Guess you like

Origin www.cnblogs.com/chailuG/p/11260102.html