Programming: Closure

I have a question about Closure, details following:
Just read the chapter on “CLOSURES” in Kirupa’s book: JavaScript absolute beginner’s guide. Specifically page 84 and on.
It reminds me of a contortionist I saw at Cirque du Soleil. Why not make startTime a global variable outside the stopWatch() function?
The getDelay() can use startTime and does not even have to be inside stopWatch().
Or am I missing something? Is it because local variables can be looked up faster than global?
Johan

That could work too. But let’s say you wanted to run two stopwatches? If a global variable was used, both of the stopwatches would have to use that same global startTime meaning one stopwatch is going to screw up the other (whichever runs second will screw up the first).

By using a closure, the variable is unique to that stopwatch instance. This works very similar to having a class with a startTime property, only with closures, instead of an object instance, you’re dealing with a callable function (and the closure variables aren’t directly exposed to calling code like class property members are)

2 Likes