Skip to content

Instantly share code, notes, and snippets.

@tonyc726
Created May 27, 2014 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyc726/cd5a9b56045327c4e540 to your computer and use it in GitHub Desktop.
Save tonyc726/cd5a9b56045327c4e540 to your computer and use it in GitHub Desktop.
通过 Object.prototype.toString.call() 进行类型判断
# http://zhang.zipeng.info/library/coffeescript/07_the_bad_parts.html
# 使用typeof
# 这里是jQuery的$.type的实现的例子
type = do ->
classToType = {}
for name in "Boolean Number String Function Array Date RegExp Undefined Null".split(" ")
classToType["[object " + name + "]"] = name.toLowerCase()
(obj) ->
strType = Object::toString.call(obj)
classToType[strType] or "object"
# Returns the sort of types we'd expect:
# type("") # "string"
# type(new String) # "string"
# type([]) # "array"
# type(/\d/) # "regexp"
# type(new Date) # "date"
# type(true) # "boolean"
# type(null) # "null"
# type({}) # "object"
// http://my.oschina.net/sfm/blog/33197
var oP = Object.prototype,
toString = oP.toString;
function typeOf(value) {
if (null === value) {
return 'null';
}
var type = typeof value;
if ('undefined' === type || 'string' === type) {
return type;
}
var typeString = toString.call(value);
switch (typeString) {
case '[object Array]':
return 'array';
case '[object Date]':
return 'date';
case '[object Boolean]':
return 'boolean';
case '[object Number]':
return 'number';
case '[object Function]':
return 'function';
case '[object RegExp]':
return 'regexp';
case '[object Object]':
if (undefined !== value.nodeType) {
if (3 == value.nodeType) {
return (/\S/).test(value.nodeValue) ? 'textnode': 'whitespace';
} else {
return 'element';
}
} else {
return 'object';
}
default:
return 'unknow';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment