What is the best way to test if an object is an instance of jQuery?
Depends on the inner workings of jQuery, but I’d go with
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.
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.
will fail, as jQuery objects only inherit the property from their prototype.
I’d also discourage using the
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.
hasOwnProperty() is never used as well. I’m not sure what this says about the code quality of the jQuery library 😉