Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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"