Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 3. CoffeeScript Idioms > Private Variables

3.11. 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"

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial