Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to understand these examples from the book javascript, The good parts [closed]

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.

like image 287
brain storm Avatar asked Dec 08 '25 23:12

brain storm


1 Answers

What he was implying in the example, I believe, was the fact that you don't have to make a copy of the status parameter and pass it to the get_status function because get_status implicitly gets access to everything enclosed within the context in which it was defined (in this case, quo)

Similarly, in example 2

enter image description here

like image 77
Lim H. Avatar answered Dec 10 '25 13:12

Lim H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!