Last active
August 29, 2015 14:04
-
-
Save flipjs/765e158ecce963deb774 to your computer and use it in GitHub Desktop.
toType() by Angus Croll
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 toType = function(obj) { | |
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() | |
} | |
toType({a: 4}); //"object" | |
toType([1, 2, 3]); //"array" | |
(function() {console.log(toType(arguments))})(); //arguments | |
toType(new ReferenceError); //"error" | |
toType(new Date); //"date" | |
toType(/a-z/); //"regexp" | |
toType(Math); //"math" | |
toType(JSON); //"json" | |
toType(new Number(4)); //"number" | |
toType(new String("abc")); //"string" | |
toType(new Boolean(true)); //"boolean" | |
/*** | |
We could get a little cleverer (inspired by Chrome’s use | |
of “global” for window.[[Class]]). By wrapping the | |
function in a global module we can identify the | |
global object too: | |
***/ | |
Object.toType = (function toType(global) { | |
return function(obj) { | |
if (obj === global) { | |
return "global"; | |
} | |
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); | |
} | |
})(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment