Skip to content
Permalink
Browse files

Fix #13075. Optimize $.type by preferring `typeof`. Close gh-1089.

Also fixes browsers where `typeof RegExp === "function"`.
  • Loading branch information...
hasclass authored and dmethvin committed Dec 18, 2012
1 parent d829804 commit 5eec75e582d27e2d4f625f6be33eabad84f16239
Showing with 17 additions and 4 deletions.
  1. +6 −3 src/core.js
  2. +11 −1 test/unit/core.js
@@ -427,9 +427,12 @@ jQuery.extend({
},

type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
if ( obj == null ) {
return String( obj );

This comment has been minimized.

Copy link
@gibson042

gibson042 Dec 24, 2012

Member

@dmethvin I missed this before, but we'd probably get better compression out of obj + "".

}
return typeof obj === "object" || typeof obj === "function" ?

This comment has been minimized.

Copy link
@DzenisevichK

DzenisevichK Dec 24, 2012

Why do not save typeof obj in var?

This comment has been minimized.

Copy link
@mikesherov

mikesherov Dec 24, 2012

Member

@DzenisevichK, because typeof is blazingly fast, and repeated strings are eaten for basically free by gzip, so this was probably smaller when gzip compressed than caching the variable.

This comment has been minimized.

Copy link
@dmethvin

dmethvin Dec 24, 2012

Member

@DzenisevichK I tried it, it was larger. Go figure.

class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},

isPlainObject: function( obj ) {
@@ -243,7 +243,7 @@ test("trim", function() {
});

test("type", function() {
expect( 24 );
expect( 28 );

equal( jQuery.type(null), "null", "null" );
equal( jQuery.type(undefined), "undefined", "undefined" );
@@ -269,6 +269,16 @@ test("type", function() {
equal( jQuery.type(document.body), "object", "Element" );
equal( jQuery.type(document.createTextNode("foo")), "object", "TextNode" );
equal( jQuery.type(document.getElementsByTagName("*")), "object", "NodeList" );

// Avoid Lint complaints
var MyString = String;
var MyNumber = Number;
var MyBoolean = Boolean;
var MyObject = Object;
equal( jQuery.type(new MyBoolean(true)), "boolean", "Boolean" );
equal( jQuery.type(new MyNumber(1)), "number", "Number" );
equal( jQuery.type(new MyString("a")), "string", "String" );
equal( jQuery.type(new MyObject()), "object", "Object" );
});

asyncTest("isPlainObject", function() {

0 comments on commit 5eec75e

Please sign in to comment.
You can’t perform that action at this time.