admin管理员组

文章数量:1200423

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?

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?

Share Improve this question asked Jan 28, 2009 at 8:28 CVertexCVertex 18.2k28 gold badges96 silver badges125 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 20

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

One of the following:

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

instanceof is recommended

Use this instead of instanceof to test for jQuery objects.

/**
 * @see http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak
 * @return Boolean True if object is of type jQuery, false otherwise
 */
function isjQuery(obj) {
    return obj && obj.hasOwnProperty && obj instanceof jQuery;
}

本文标签: What39s the correctproper way to test if an object is a jQuery object in javascriptStack Overflow