toType() - fix typeof
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
by Yury
JavaScript
/*http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/*/
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"
/*--------------------------------------*/
/*
Alternatively you might choose to add the toType function to a namespace of your own, such as util.
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)
Object.toType(window); //"global" (all browsers)
Object.toType([1,2,3]); //"array" (all browsers)
Object.toType(/a-z/); //"regexp" (all browsers)
Object.toType(JSON); //"json" (all browsers)
//etc..