Last active
June 17, 2016 19:23
-
-
Save matheuseduardo/9f3a80685e20885f57d0ca0b6f3c11cf to your computer and use it in GitHub Desktop.
get type of objects, errors, etc. in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var type = (function (global) { | |
var cache = {}; | |
return function (obj) { | |
var key; | |
return obj === null ? 'null' // null | |
: obj === global ? 'global' // window in browser or global in nodejs | |
: (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function | |
: obj.nodeType ? 'object' // DOM element | |
: cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math | |
|| (cache[key] = key.slice(8, -1)); // get XXXX from [object XXXX], and cache it | |
}; | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment