I am reading javascript: The good parts by Douglas Crockford. I am having difficulty in understanding a particular example and the explanation that author provides.
example 1: (pg 38)
var quo=function (status) {
return {
get_status:function() {
return status;
}
};
};
var myQuo=quo("amazed");
document.writeln(myQuo.get_status());
The explanation from book (I do not understand this. please explain this part):
This quo function is designed to be used without the new prefix, so the name is not capitalized.when we call quo, it returns a new object containing a get_status method. A reference to that object is stored in myQuo. The get_status method still has privileged access to quo's status property even though quo has already returned. get_status does not have access to a copy of the parameter. it has access to the paramter itself. This is possible because the function has access to the context in which it was created. This is called closure.
example 2(pg 39):
//make a function that assigns event handler function to array of nodes
//when you click on a node, an alert box will display the ordinal of the node
var add_the_handlers=function (nodes) {
var helper=function(i) {
return function(e) {
alert(i);
}
};
var i;
for (i=0;i<nodes.length;i++) {
nodes[i].onclick=helper(i);
}
};
I am having difficultly to understand how this code works and moreover what function(e) does? why helper function return function that in turn return nothing. Its very confusing to me. if somebody can explain in simple language, it will be very helpful. Thanks a lot
EDIT:
According to the book is the bad example for the above(example 2):
var add_the_handlers=function(nodes) {
var i;
for (i=0;i<nodes.length;i++) {
nodes[i].onclick=function(e) {
alert(i);
};
}
};
The author cites this as bad example because it always displays the number of nodes.