Created
April 30, 2014 18:28
-
-
Save ndelage/06354f646aac73387060 to your computer and use it in GitHub Desktop.
Immediately Invoked Function Expression (IIFE)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var elems = $('a'); | |
// WITHOUT THE IIFE | |
// | |
// In the following example, the alert text "I am i", will always | |
// print '3' because that's the last value for i (after the loop | |
// finishes). If we want to retain the value of i when we bind | |
// the click handler, we can use an IIFE to save the value of i | |
// in the IIFE's execution context | |
for(var i=0; i<elems.length; i++) { | |
$(elems[i]).on('click', function(e){ | |
e.preventDefault(); | |
alert( 'I am link #' + i ); | |
}); | |
} | |
// WITH THE IIFE | |
// | |
// Now, with the IIFE on line 25, the value of i | |
// is retained in the IIFE's execution context. So | |
// the console.log("I am link #:" + index) will print | |
// the correct index value for each link when clicked. | |
for(var i=0; i<elems.length; i++) { | |
(function(index) { | |
$(elems[index]).on('click', function(e){ | |
e.preventDefault(); | |
alert( 'I am link #' + index ); | |
}); | |
})(i); | |
} | |
// Here's a link to a JS Fiddle that demonstrates the IIFE: | |
// http://jsfiddle.net/SaTW6/ | |
// For more IIFE knowledge, checkout this link: | |
// http://benalman.com/news/2010/11/immediately-invoked-function-expression/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment