Revealing Module Pattern in CoffeeScript

My friend Colin introduced me to CoffeeScript last week through Mindscape’s Web Workbench.  As I started to learn CoffeeScript, the first thing I wanted to do is to hand translate some of my JavaScript files to see how the CoffeeScript compiler would convert them to JavaScript so I would end up with the functionally same code in the end.

I use the Revealing Module Pattern quite a bit. I found an implementation written by Burk Holland and in the comments of Burk’s post Steve Howell and Elijah Manor provided additional implementations.  Although, Burk’s example came close to what I was looking for in simplicity and cleanliness, I felt that there could be some improvements:

  • It defined the module in the global namespace.  I always create my modules in a namespace I define for the my project to further protect against naming collisions.
  • I didn’t like how the module ended with the definition of a variable to contain the  public functions.

I put forward the following:

I use the existential operator to use my project’s namespace if already defined or to create a new one.  Although, the || operator does produce nicer JavaScript output.  I’m sitting on the fence to which way to go.

I create an object as the last expression in the function that will be returned.  This skips the creation of the temporary variable that is never referenced. 

I’m pretty happy with the JavaScript that is produced.  It very closely matches how I implement the Revealing Module pattern in JavaScript, and it upholds the simplicity and cleanliness of CoffeeScript.