Private Variables

The do keyword in CoffeeScript lets us execute functions immediately, a great way of encapsulating scope and protecting variables. In the example below, we’re defining a variable classToType in the context of an anonymous function which is immediately called by do. That anonymous function returns a second anonymous function, which will be the ultimate value of type. Since classToType is defined in a context in which no reference is kept, it can’t be accessed outside that scope:

# Execute function immediately
type = do ->

  types = [
    "Boolean"
    "Number" 
    "String" 
    "Function" 
    "Array" 
    "Date" 
    "RegExp"
    "Undefined" 
    "Null"
  ]

  classToType = {}
  for name in types
    classToType["[object " + name + "]"] = name.toLowerCase()

  # Return a function
  (obj) ->
    strType = Object::toString.call(obj)
    classToType[strType] or "object"

In other words, classToType is completely private, and can never again be referenced outside the executing anonymous function. This pattern is a great way of encapsulating scope and hiding variables.

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.