concept closure in category coffeescript

appears as: closures, closure, closure
CoffeeScript in Action

This is an excerpt from Manning's book CoffeeScript in Action.

If closures are new to you but you’re comfortable with objects, then you might think of a closure as an object. Suppose you had an incrementer object with a single method called increment that incremented an internal value and returned it. This would be essentially the same thing as the closure demonstrated in this section.

The returned function has access to the variables scoped to makeIncrementer. The returned function closes over the variables in scope, resulting in closure. Each time makeIncrementer is invoked, a new closure is created, meaning you can have several of them:

3.6.3. Extended example: using closure

The new watchedFileReader function allows you to now solve the problem without having to have a global variable to share state around the program. Here’s a modification of the program from listing 3.4 that uses closures and serves the combined contents of multiple files.

Listing 3.6. Serve multiple files

Using closure, you’ve been able to isolate two parts of your program and provide a way to get data from one part of a program to another.

if true let x = 2, y = 2 console.log 'let expression' console.log 'wraps block in closure'