hi, i didnt understood this ,
" The value x is out of bonds by the time you call the functions. So x is a closure variable, and the value of it is list.length+1 by the time the function finished executing. " the variable x is declared in first for-loop, so its scope is just for the loop. from my understanding array arrFun holds a function at index 0,1,2 each. now when i call function buildList() from fn27(), the buildList returns array of functions as mentioned above, now if i iterate the array arr using variable x, this x has nothing to do with the x declared in the for-loop of function buildList for array creation arrFun, now what i expect is arr should be iterated using x from 0,1,2. and arr should be holding fn0, fn1, fn2 so can you please clear my confusion, were i am going wrong. On Oct 21, 7:45 pm, Poetro <[email protected]> wrote: > 2011/10/21 Rahul <[email protected]>: > > > > > > > > > > > function buildList(list){ > > var arrFun = new Array(); > > for(var x = 0; x < list.length; x++){ > > arrFun[x] = function() > > { alert(" NUMBER "+list[x]); } > > } > > return arrFun; > > } > > > function fn27(){ > > var arr = buildList([23,45,67]); > > for(var x = 0; x < arr.length; x++){ > > arr[x](); > > } > > } > > > window.onload = fn27(); > > > here, on page onload there is a three times alert as "NUMBER > > undefined", > > why so ? > > why list[x] is not holding the value which was assigned initially. > > > waiting for the reply > > The value x is out of bonds by the time you call the functions. So x > is a closure variable, and the value of it is list.length+1 by the > time the function finished executing. This gives you an undefined > value, as there is no defined value for that index in the array. There > are several ways to fix that. > > function buildList(list) { > var arrFun = []; > function callback(y) { > // y is a closure variable > return function() { > alert(" NUMBER " + list[y]); > }; > } > for (var x = 0; x < list.length; x++) { > arrFun[x] = callback(x); > } > return arrFun; > > } > > -- > Poetro -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
