JS: Good parts - Ch.4 - Functions

closures 2

by Denise Nepraunig

HTML

<div>hello</div>
<div>world!</div>
<div>how</div>
<div>are</div>
<div>you</div>
<div>doing?</div>

CSS

div {
    width: 100px;
    height: 100px;
    margin: 15px;
    background-color: teal;
    float: left;
}

JavaScript

/* 
All texts and infos I have taken from:
'JavaScript: The Good Parts' by Douglas Crockford
*/

// closure 2
// the inner function does not get a 'copy' to the outer variable
// it gets the actual value

// BAD example
/*
var add_handlers = function add_handlers(nodes) {
    var i;
    for (i = 0; i < nodes.length; i++) {
        nodes[i].onclick = function(e) {
            alert(i)
        };
    }
};
*/

// so never create functions in a loop, use an outside helper function
var add_handlers = function add_handlers(nodes) {
    var helper = function helper(i) {
        return function(e) {
            alert(i);
        };
    };
    var i;
    for(i = 0; i < nodes.length; i++) {
        nodes[i].onclick = helper(i);
    }
};
var divNodes = document.getElementsByTagName('div');
add_handlers(divNodes);