public
Last active

Object.toType

  • Download Gist
ba-objecttotype.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// 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));

I dig the Global check. Imma add that to my projects that have similar methods. I will post a link when I update it to detect global on server-side enviros too.

cowboy
yeah good call on the IE7 / IE8 undefined/null issue (your second "// If the object is undefined, return "Null" (IE <= 8)" is wrong :-)

jd - I did the global check in my original article too :-;

@angus-c You win double internets \o/

@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.

The code is wicked - it's the comment...

  // If the object is undefined, return "Null" (IE <= 8)

should say
// If the object is undefined, return "Undefined" (IE <= 8)

On Aug 9, 2011, at 5:11, cowboyreply@reply.github.com wrote:

@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.

Reply to this email directly or view it on GitHub:
https://gist.github.com/1131946

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.