Thursday, 22 August 2013

Learning Javascript, why do these two functions behave differently?

Learning Javascript, why do these two functions behave differently?

Learning Javascript and can't figure out why these two functions are
different. I saw this example (I added names to the functions):
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
setTimeout((function myBind(msg) {
return function myAlert() { alert(msg); }
})(txt[i]), 1000);
}&#8203;
I see that a function that calls alert is being returned. So I thought,
why not just return it directly:
var txt = ["a","b","c"];
for (var i = 0; i < 3; ++i ) {
setTimeout( function() { alert(txt[i]);} ,1000);
}&#8203;
This ends up alerting 'undefined.' I understand that it's because it's
trying to access txt[3] because after one second the loop has finished and
i has been set to 3, but I don't understand how the original setup avoided
this problem.

No comments:

Post a Comment