JavaScript-- on closure (closure)

js code before execution will do several things:

1. Detection Code

2. precompiled : Before the implementation of the code will code functions and variables declared in advance and do some other processing

  1. In the moment before execution function, generates an OA (object action) Object

  2. The shape property values ​​as a function of parameters of the objects OA property name, as the argument object AO

  3. Analyze var statement, the variable name as the property name AO object value is undefined, variables and parameters of the same name if they do not do any change

  4. Analysis of function declaration, a function name as the attribute name AO object value is a function thereof, a function of the same name if they are directly covered

Now let's analyze this code :( take four steps in accordance with pre-compiled)  

  function fun(a){ 
  console.log(a)
  var a = 100
  console.log(a)
  }
  fun(10)

  1. an object before performing fun OA fun,

  2. The function shape parameter a = 10, AO objects stored

  3.var declared a a value is undefined 

  4. Analysis Function This function, there are no inner function

After doing the above analysis again the implementation of this program execution across a variable output or change the value of the object OA went looking for:

  console.log (a) At this time, the output 10 a = 10

  a = 100 此时 a = 100

  console.log (a) 100 Output

This entire process is executed a function, the closure is formed in a nested function which one or more functions, let us analyze the next closure

  function a(){
    var num = 100;
    function b(){
      num ++;
      console.log(num)
    }
    return b;
  }
  var fun = a()
  fun()
  fun()

OA object 1. Generate a a () before execution

2. No parameter

3. Declare var num = undefined

3. Statement function B () member function is

Then performs a () to copy num 100, and then returns B () function fun = function b () {} In the next execution to fun () when:

1. an object OA () before execution fun

2. No parameter

3. There is no var declaration

4. No function declaration

Then execute b () function, this time num ++, will first () to find its role in the num b there if this variable is not to look down the scope chain num 

Find a () There are num variable This is a () of num ++ implementation of the operation so a num () will change in the num = 101

And performing a subsequent post fun () a fun all operating on the same but this time num = 101 then ++ operator a () in num = 102

Change of the image represented by the execution of the entire program occurring OA

* Throughout the program execution it should be noted that most functions executed once will have a respective objects OA

Even long will perform the same function again produce a corresponding active object OA

  

    

     

    

    

Guess you like

Origin www.cnblogs.com/blogzzy/p/11369684.html