javascript - how to create new callback function -
in code below i'm adding callback function list in loop.
every item in list call call log >>item30
can please tell me why? there way create new function() call can log
item0 item1 item2 item3 item4 , on ....... ......
(var j = 0 ; j < 30 ; j += 1) { addthisthingtolist(function () { console.log( "item" +j ); }); }
this happens if function addthisthingtolist() using asynchronous behavior (like ajax calls) , callback called time later after for loop has run course , it's index value @ ending value.
you can fix closure freeze loop value separately each call addthisthingtolist() this:
(var j = 0 ; j < 30 ; j += 1) { (function(index) { addthisthingtolist(function () { console.log( "item" + index); }); })(j); } working demo: http://jsfiddle.net/jfriend00/a5cjg/
by way of explanation, iife (immediately invoked function expression). variable j passed iife , becomes named argument function named index. then, inside function, can refer index value of j frozen uniquely , separately each call addthisthingtolist(). have named argument index j in case have overriden higher scoped j, prefer use separate variable name more clear what.
here's reference on iife concept if want read more it:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Comments
Post a Comment