JavaScript Closures: An Example

Here is a common problem that will face any JavaScript developer sooner or later. The code below, as simple as it looks, introduces a bug that might not be picked up by the developer during unit testing.

   for(var i = 1; i<6; i++) {
        var div = document.getElementById(‘div’ + i);       
        div.onclick = doAlert(‘Al’ + i);       
    }

The problem is that all elements that have the event attached will alert the same value. The solution is to use JavaScript Closures illustrated in the code below.

   for(var i = 1; i<6; i++) {
        var div = document.getElementById(‘div’ + i);       
        div.onclick = doAlert(‘Al’ + i);       
    }

    function doAlert(what) {
        return function() {
            alert(what);
        }
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: