Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct/proper way to test if an object is a jQuery object in javascript?

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?

like image 939
CVertex Avatar asked Jan 28 '09 08:01

CVertex


1 Answers

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

like image 107
7 revs Avatar answered Oct 14 '22 23:10

7 revs