Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created August 8, 2011 15:22
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowboy/1131946 to your computer and use it in GitHub Desktop.
Save cowboy/1131946 to your computer and use it in GitHub Desktop.
Object.toType
// See http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
(function(global) {
// Maintain a map of already-encountered types for super-fast lookups. This
// serves the dual purpose of being an object from which to use the function
// Object.prototype.toString for retrieving an object's [[Class]].
var types = {};
// Return a useful value based on a passed object's [[Class]] (when possible).
Object.toType = function(obj) {
var key;
// If the object is null, return "Null" (IE <= 8)
return obj === null ? "Null"
// If the object is undefined, return "Undefined" (IE <= 8)
: obj == null ? "Undefined"
// If the object is the global object, return "Global"
: obj === global ? "Global"
// Otherwise return the XXXXX part of the full [object XXXXX] value, from
// cache if possible.
: types[key = types.toString.call(obj)] || (types[key] = key.slice(8, -1));
};
}(this));
@jdalton
Copy link

jdalton commented Aug 9, 2011

@angus-c You win double internets \o/

@cowboy
Copy link
Author

cowboy commented Aug 9, 2011

@angus-c why is it wrong? If obj === null then obj is null. If that check fails, if obj == null then obj must be undefined.

@angus-c
Copy link

angus-c commented Aug 9, 2011 via email

@cowboy
Copy link
Author

cowboy commented Aug 9, 2011

@angus-c hahaha thanks, fixed! I think I need more sleep.

@gotofritz
Copy link

I know this is ancient code, but for anyone stumbling on this today (mid 2014), note that PhantomJS currently returns "DomWindow" for both undefined and null (it's a known bug, but still)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment