I was working on a specific example on CodeSchool that is supposed to exemplify closure. I'm having trouble understanding a simple concept. Could someone point me in the right direction?
function warningMaker( obstacle ){
var count=0;
return function ( number, location ) {
count++;
alert("Beware! There have been " +
obstacle +
" sightings in the Cove today!\n" +
number +
" " +
obstacle +
"(s) spotted at the " +
location +
"!\n" + "This is Alert #" + count+" today for" +obstacle+ " danger."
);
};
}
In this function, if I define, var penguin=warningMaker('penguin'). Then I call penguin(1,'Boston') as an example. The count will be returned as 1. Each time I call this function, the count number increases.
I'm having trouble understanding how this could happen!? Doesn't the 'var count=0' get called each time that the function is called? Wouldn't that reset the value of the count variable?