Closures are an extension of the concept of scope — functions have access to variables that were available in the scope where the function was created. If that’s confusing, don’t worry: closures are generally best understood by example.
In Example 2.44, “Functions can "see" changes in variable values after the function is defined” we saw how functions have access to changing variable values. The same sort of behavior exists with functions defined within loops -- the function "sees" the change in the variable's value even after the function is defined, resulting in all clicks alerting 5.
Example 2.46. How to lock in the value of i
?
/* this won't behave as we want it to; */ /* every click will alert 5 */ for (var i=0; i<5; i++) { $('<p>click me</p>').appendTo('body').click(function() { alert(i); }); }
Example 2.47. Locking in the value of i
with a closure
/* fix: “close” the value of i inside createFunction, so it won't change */ var createFunction = function(i) { return function() { alert(i); }; }; for (var i=0; i<5; i++) { $('<p>click me</p>').appendTo('body').click(createFunction(i)); }
Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.