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 ;)