0

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?

  • 1
    It gets called each time `warningMaker()` is called (once in your case), but the initialization is outside of the `penguin()` function, so it's never reset. – Paul Roub Apr 22 '14 at 20:18
  • `penguin` contains the value *returned* by `warningMaker`, which is a function. That function does not contain `var count=0;`. – Felix Kling Apr 22 '14 at 20:23
  • possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Felix Kling Apr 22 '14 at 20:25

2 Answers2

0

warningMaker is only called once to create the penguin object. When warningMaker is called, variable count is created within its scope, and returns a function that is assigned to penguin. Since that returned function is defined within warningMaker, it has access to its scope and, thus, to variable "count".

Closures are a common technique to create the functionality of private variables/methods in JavaScript.

A good resource to understand closures can be found here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

Best.

E. Valencia
  • 447
  • 2
  • 6
0

In your example the way closure works is it basically creates a count variable and keeps it in memory. And then your warningMaker function returns another function. The function that it returns is the one thats being executed every time you call warningMaker() with parametes.

Alex Shilman
  • 1,547
  • 1
  • 11
  • 15