Below is a quick example of an object with four functions that are actually closures.
reset. They all act on a variable called
count, which sits within the immediately invoked function expression (IIFE) holding the closure.
Each function, which comes bundled with its surrounding environment, is a closure.
getmethod will simply get the
setmethod sets the
countvalue to any value we want.
incrementmethod will increment the existing value by the amount passed in as a parameter. If no value is passed in, it increments the value by 1.
resetmethod resets the value to zero.
These methods are the only way the user can access the
count value. In this way, the use of a closure causes the
count value to act in a similar way to that of a private variable in a Java object; it cannot be accessed outside the object, so methods are required to retrieve its value or update it.
In the demo, you will see that an
init method grabs some references to the HTML elements we print to and then calls all the methods. Take a look at how they are called and see if you can understand what causes these particular values to be printed out.
I hope this quick post gives you a solid idea of what closures are about. Thanks for reading!