JS Advanced --- closure case, a plurality of the same random number

Closure case, a plurality of generating the same random number

 

    Summary: If you want to cache data, put the data in the middle of a function of position and function of the inner layer of the outer layer
    Closure effect: the data buffer; advantage is defective, no timely release

  •     Local variables in the function, after the function using local variables will be automatically released
  •     After closure, the use of local variables inside the scope chain will be extended

 

3 generated random number (random, different)

    function showRandom() {
      var num=parseInt(Math.random()*10+1);
      console.log(num);
    }

    show random ();
    show random ();
    show random ();

 

Bag closure embodiment, generates three random numbers, but all the same
   function f1() {
      var num=parseInt(Math.random()*10+1);
      return function () {
        console.log(num);
      }
    }

    where ff = f1 ();

    ff();
    ff();
    ff();

 

 

Guess you like

Origin www.cnblogs.com/jane-panyiyun/p/12175234.html