leodutra
6/2/2014 - 5:36 PM

JavaScript obtain/ get type of object (enhanced typeof)

JavaScript obtain/ get type of object (enhanced typeof)

// SHOWS JS TYPES ONLY based on Object.prototype.toString.call result
// any non JavaScript type will be returned as 'object'
type = (function() {

  'use strict';

  var BASE = "Array Object Function RegExp String Boolean Number Undefined Null Date Error".split(' ');
  var TYPES = {};
  var TO_STRING = TYPES.toString;
  
  for (var i = BASE.length, type; i--;) {
    type = BASE[i];
    TYPES["[object " + type + "]"] = type.toLowerCase();
  }
  
  return function(any) {
    
    if (any == null) { // undefined is true too
      return any + '';
    }
    
    var type = typeof any;
    return type == 'object' || type == 'function' ?
      TYPES[ TO_STRING.call(any) ] || 'object' : type;
      
  };
  
})();