Oct 21, 2009

javascript reflection in jQuery

String: typeof object === "string"
Number: typeof object === "number"
Boolean: typeof object === "boolean"
Object: typeof object === "object"
Function: jQuery.isFunction(object)
Array: jQuery.isArray(object)
Element: object.nodeType
null: object === null
undefined: typeof variable === "undefined" or object.prop === undefined
null or undefined: object == null


 toString = Object.prototype.toString,
 
 //var x = { name :"fred" };
    //alert(x.hasOwnProperty("name"));
 hasOwn = Object.prototype.hasOwnProperty,

 push = Array.prototype.push,

 isFunction: function( obj ) {
  return toString.call(obj) === "[object Function]";
 },

 isArray: function( obj ) {
  return toString.call(obj) === "[object Array]";
 },

 isPlainObject: function( obj ) {
  // Must be an Object.
  // Because of IE, we also have to check the presence of the constructor property.
  // Make sure that DOM nodes and window objects don't pass through, as well
  if ( !obj || 
    toString.call(obj) !== "[object Object]" || 
    obj.nodeType || 
    obj.setInterval ) {
    
   return false;
  }
  
  // Not own constructor property must be Object
  if ( obj.constructor &&
   !hasOwn.call(obj, "constructor") &&
   !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
   return false;
  }
  
  // Own properties are enumerated firstly, so to speed up,
  // if last one is own, then all properties are own.
 
  var key;
  for ( key in obj ) {}
  
  return key === undefined || hasOwn.call( obj, key );
 },

 isEmptyObject: function( obj ) {
  for ( var name in obj ) {
   return false;
  }
  return true;
 },

isWindow: function( obj ) {
 return obj && typeof obj === "object" && "setInterval" in obj;
},

//new in jQuery 1.4
$.type(object);