Question: I need help with doing a JavaScript closure on the following code. I am not fully understanding how to do closure. Below is the problem
I need help with doing a JavaScript closure on the following code. I am not fully understanding how to do closure. Below is the problem statement.
This one is a real gotcha for many people, so you need to understand it. Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function buildList(list) { var result = []; for (var i = 0; i < list.length; i++) { var item = 'item' + list[i]; result.push( function() {alert(item + ' ' + list[i])} ); } return result; }
function testList() { var fnlist = buildList([1,2,3]); // using j only to help prevent confusion - could use i for (var j = 0; j < fnlist.length; j++) { fnlist[j](); } } |
The line result.push( function() {alert(item + ' ' + list[i])} adds a reference to an anonymous function three times to the result array. If you are not so familiar with anonymous functions think of it like:
?
| 1 2 | pointer = function() {alert(item + ' ' + list[i])}; result.push(pointer); |
Note that when you run the example, "item3 undefined" is alerted three times! This is because just like previous examples, there is only one closure for the local variables for buildList. When the anonymous functions are called on the line fnlist[j](); they all use the same single closure, and they use the current value for i and item within that one closure (where i has a value of 3 because the loop had completed, and item has a value of 'item3').
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
