-1

I have known the key of closure is about scope. But I don't know the specific execution order of it.

A classical code from 《Professional JavaScript for Web Developers 3rd Edition》about closures.

function createFunctions(){
 var result=new Array();
 alert('haha');
 for(var i=0;i<10;i++){
  result[i]=function(){
   alert(i);
   return i;
  };
 }
 return result;
}
var a=createFunctions();

To my surprise, 'haha' was alerted while none of 'i' were alerted.I was just assigning the function to variable a.Why the statement "alert('haha')" was alerted while the cycle wasn' t executed?

when I add the below code,

 var a=createFunctions();
    alert(a[2]);
why it alerted like this

function (){
       return i;
      }

not like

function (){
          return 2;
          }

Furthermore when I add the below code, what will being the order of statements executed especially the statements in the cycle.

    var a=createFunctions();
       alert(a[2]());
zyMacro
  • 675
  • 7
  • 14
  • Why should `i`s be alerted? You're never calling those functions. Also, all the functions within the array when ever run will alert you 10... – Teemu Jan 05 '17 at 06:40
  • That book is quite old. I suggest you find one that is more up-to-date. –  Jan 05 '17 at 07:25

2 Answers2

1

When you call

var a=createFunctions() 

alert('haha') is executed immediately, and an array of 10 functions is created and assigned to the variable 'a', each function alerting 'i' and returning it.

However, by the time any of those functions is called (provided you call them after creating them) the value of i is '10' (the loop termination value). So every time you call one of the functions, with

alert(a[x]()) 

( with any value of x = 0 thru 9 ) it will alert(10) as the function executes and alert(10) again when it returns.

0

Why the statement "alert('haha')" was alerted

Because it was an alert statement in the function you called.

while the cycle wasn' t executed

The cycle was executed. The cycle just creates some functions and assigns them to positions in an array. You never call any of those functions.

and when I add the below code, what will being the order of statements executed

It depends where you add it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335