views:

332

answers:

3

I'm writing a javascript function and in "compact" javascript design fashion, the type/length of arguments changes the behaviour of the function. One possible type of the argument is a jQuery object, for which I would like very special logic.

What is the best way to test if an object is an instance of jQuery?

A: 

This thread has a few suggestions

Bill Zeller
+5  A: 

One of the following:

obj instanceof jQuery
obj && obj.constructor == jQuery
obj && obj.jquery

instanceof is recommended

VonC
what about: "jquery" in obj?
Tomalak
+7  A: 

Depends on the inner workings of jQuery, but I'd go with

obj instanceof jQuery

It's the most 'JavaScript way' of doing it. Keep in mind that it will fail when passing objects between window/frame boundaries!

Tomalak's suggestion

'jquery' in obj

should still work in this case, so you should use it if you expect to do multi-window data exchange. I wouldn't recommend it as a general solution, as just looking for a property named 'jquery' isn't very reliable.

The in operator will also throw an error if obj is a primitive. If this behaviour is undesired, you might consider using one of these tests instead:

obj && obj.jquery
'jquery' in Object(obj)

I find the second one more appealing, but the first one will likely be faster.

Checking

Object(obj).hasOwnProperty('jquery')

will fail, as jQuery objects only inherit the property from their prototype.

I'd also discourage using the constructor property for type checking in JavaScript - it might work reliably for jQuery, but as constructor is just a property of the object pointed to by the constructor function's prototype property at instantiation time, there are lots of ways to mess with such tests...


As a side note:

jQuery itself checks for obj && obj.jquery. It does not use instanceof even once. Instead, it uses a combination of typeof, duck-typing and toString.call() for type checking, which should work where instanceof will fail.

Also, hasOwnProperty() is never used as well. I'm not sure what this says about the code quality of the jQuery library ;)

Christoph
Much more detailed than my post: +1 and I recommend your post to be chosen as the answer
VonC
You got my vote for mentioning the failure of instanceof across window/frame boundaries!
Crescent Fresh