Skip to content

Instantly share code, notes, and snippets.

@bogdanbiv
Forked from cowboy/ba-objecttotype.js
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bogdanbiv/c2b8c1ded9dad6cf5f2e to your computer and use it in GitHub Desktop.
Save bogdanbiv/c2b8c1ded9dad6cf5f2e to your computer and use it in GitHub Desktop.
// 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));
@bogdanbiv
Copy link
Author

Note: correct line 15: from " == null " to " === undefined ", I do not see the point of comparing for null twice.

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