简体   繁体   中英

Need Help Understanding JavaScript script

I'm very new to JavaScript and I'm trying to understand the flow of this particular script (it's an example from a textbook).

var clunkCounter = 0;
thingamajig(5);
console.log(clunkCounter);


function clunk(times){
 var num = times; 
 while (num > 0){
     display("clunk");
     num = num - 1; 
 }
}

function thingamajig(size){
 var facky = 1;
 clunkCounter = 0;
 if (size == 0){
    display("clank");
}
else if (size ==1){
    display("thunk");
}
else{
    while (size > 1){
        facky = facky * size; 
        size = size - 1; 
    }
    clunk(facky); 
 }
}

function display(output){
 console.log(output);
 clunkCounter = clunkCounter + 1;
}

I know that the result of this particular set of functions calls is that the string "clunk" should be outputted to the console 120 times, and then the value 120 should be outputted to the console.

My question is this - why declare the global variable clunkCounter and set its value to 0, only to do the same thing within the thingamajig function? Is this not redundant? I know that if the var clunckCounter = 0; statement didn't exist, the same effect would be achieved (without declaring clunkCounter with the 'var' keyword within the the thingamajig function, it becomes a global rather than local variable). Am I correct in this assumption?

It looks like the author wants clunkCounter to be reset to 0 every time thingamajig is called because display (which thingamajig calls) modifies the counter.

The purpose of the original declaration of clunkCounter is to make it global, and the initialization is redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM