Skip to content

Instantly share code, notes, and snippets.

@rkatic
Created August 28, 2011 15:03
Show Gist options
  • Save rkatic/1176771 to your computer and use it in GitHub Desktop.
Save rkatic/1176771 to your computer and use it in GitHub Desktop.
Object type inquiry enhancments via $.nativeType()
(function( jQuery, undefined ){
var toString = ({}).toString,
hasOwn = ({}).hasOwnProperty,
slice = [].slice,
push = [].push,
// [[Class]] --> type (for all natives)
class2type = {},
// Used to test if an object is a host one - IE6-8 only.
testSlice = function( obj ) {
try {
slice.call( obj, 0, 0 );
return true;
} catch (e) {
return false;
}
};
// If not IE6-8, do not use the slice test!
if ( testSlice( window ) ) {
testSlice = 0;
}
// First 3 has to be considered objects.
// (There is no a strong cross-browser way to detect arguments.)
jQuery.each("Object Arguments Math Boolean Number String Function Array Date RegExp".split(" "), function( i, name ) {
class2type[ "[object " + name + "]" ] = i < 3 ? "object" : name.toLowerCase();
});
// Returns "" for not natives.
jQuery.nativeType = function( obj ) {
if ( obj == null ) {
return "" + obj;
}
var type = class2type[ toString.call( obj ) ];
return !type || testSlice && type === "object" &&
( !("hasOwnProperty" in obj) || "setInterval" in obj && !testSlice(obj) ) ?
"" : type;
};
jQuery.isWindow = function( obj ) {
return !jQuery.nativeType( obj ) && "setInterval" in obj;
};
jQuery.isPlainObject = function( obj ) {
if ( !obj || jQuery.nativeType( obj ) !== "object" ||
// Not own constructor property must be Object.
obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype || {}, "isPrototypeOf") ) {
return false;
}
// All (enumerable) properties should be own (not inherited).
for ( var name in obj ) {
if ( !hasOwn.call( obj, name ) ) {
return false;
}
}
return true;
};
jQuery.makeArray = function( obj, ret ) {
ret = ret || [];
if ( obj != null ) {
var native_type = jQuery.nativeType( obj );
if ( native_type === "array" ) {
push.apply( ret, obj );
} else if ( obj.length == null || ( native_type ? native_type !== "object" : "setInterval" in obj ) ) {
push.call( ret, obj );
} else {
jQuery.merge( ret, obj );
}
}
return ret;
};
//------------------------------
// EXAMPLES:
jQuery.isNode = function( obj ) {
return !jQuery.nativeType( obj ) && "nodeType" in obj && !( "setInterval" in obj );
};
jQuery.xtype = function( obj ) {
return jQuery.nativeType( obj ) ||
// Test if window first because it can easily contain other properties too.
"setInterval" in obj && "window" ||
"nodeType" in obj && "node" ||
"item" in obj && "length" in obj && "list" ||
"";
};
jQuery.isjQuery = function( obj ) {
return typeof obj === "object" && "jquery" in obj && !hasOwn.call( obj, "jquery" );
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment