Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created January 18, 2010 14:28
Show Gist options
  • Save cowboy/280043 to your computer and use it in GitHub Desktop.
Save cowboy/280043 to your computer and use it in GitHub Desktop.
The Miller Device - jQuery Plugin
// based on http://zaa.ch/1q
$.isType = function( obj, type ) {
var opt = Object.prototype.toString,
result = opt.call( obj ).slice( 8, -1 ).toLowerCase();
if ( type === 'null' || type === 'undefined' ) {
type = type === 'null' ? opt.call( null ) : opt.call( undefined );
type = type.slice( 8, -1 ).toLowerCase();
}
return result === type;
};
/*
// these should all return true
$.isType( {}, 'object' );
$.isType( [], 'array' );
$.isType( 1, 'number' );
$.isType( NaN, 'number' );
$.isType( Infinity, 'number' );
$.isType( function(){}, 'function' );
$.isType( true, 'boolean' );
$.isType( new Date(), 'date' );
$.isType( /omg/, 'regexp' );
$.isType( null, 'null' );
$.isType( undefined, 'undefined' );
*/
@jdalton
Copy link

jdalton commented Aug 26, 2010

This code is needlessly complex and will cause false matches for $.isType(window, 'null'); in current browsers.
I don't agree with the name of the plugin but...

A better approach:

$.isType = function( obj, type ) {
  var result = obj == null ? String( obj ) : {}.toString.call( obj ).slice( 8, -1 ).toLowerCase();
  return result == type;
};

@cowboy
Copy link
Author

cowboy commented Aug 26, 2010

I'm not sure what kind of crack I was smoking at the time, but it seemed important for me to have those extra checks in there. Thanks, JD!

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