Created
November 21, 2013 12:42
-
-
Save adamcbrewer/7580916 to your computer and use it in GitHub Desktop.
JS: A Better typeof operator
This file contains hidden or 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
/** | |
* A better, more reliable way to handle `typeof` checking. | |
* | |
* @source http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/ | |
* | |
*/ | |
Object.toType = function(obj) { | |
return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); | |
} | |
// 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) | |
// Usage | |
Object.toType([1,2,3]); //"array" | |
Object.toType(/a-z/); //"regexp" | |
Object.toType(JSON); //"json" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment