Skip to content

Instantly share code, notes, and snippets.

@adamcbrewer
Created November 21, 2013 12:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcbrewer/7580916 to your computer and use it in GitHub Desktop.
Save adamcbrewer/7580916 to your computer and use it in GitHub Desktop.
JS: A Better typeof operator
/**
* 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