Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions chapters/classes_and_objects/type-function.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,20 @@ You'd like to know the type of a object without using typeof. (See http://javasc
Use the following function:

{% highlight coffeescript %}
type = (obj) ->
if obj == undefined or obj == null
return String obj
classToType = new Object
for name in "Boolean Number String Function Array Date RegExp".split(" ")
classToType["[object " + name + "]"] = name.toLowerCase()
myClass = Object.prototype.toString.call obj
if myClass of classToType
return classToType[myClass]
return "object"
type = (obj) ->
if obj == undefined or obj == null
return String obj
classToType = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regexp',
'[object Object]': 'object'
}
return classToType[Object.prototype.toString.call(obj)]
{% endhighlight %}

## Discussion
Expand Down