Javascript closures within an iteration.

An example of passing in the iteration value to a closure function using a self executing anonymous function.

for (var i = 0; i < links.length; i++)
{
	links[i].addEventListener('click', (function (n) {
		return function () {
			items[n].show(); // do something
		};
	})(i));
}
This entry was posted in JavaScript and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">