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


I am writing a JavaScript function and in the "compact" JavaScript design fashion, the argument / type length / program. A potential type of argument is a jQuery object, for which I want very special arguments.

If an object is an example of jQuery, then what is the best way to test it?

Depends on the internal functioning of jQuery, but I

  Obj instanceof jquery  

The most 'javascript path' to do this is to keep in mind that it will fail to pass the object between window / frame boundaries!

Tomcat's suggestion

  obj  should still work in this case, so if you have multi- If you want to exchange windows data then it should be used. I would not recommend this as a general solution, because just looking for a property named 'jquery' is not. 

In the operator will also put an error if obj is a primitive. If this behavior is unwanted, you may consider using one of these tests:

  obj & amp; Obj.jquery 'jquery' object (obj)  

I find another one more attractive, but the first one can be faster.

Check

  Object (obj). HasOwnProperty ('jquery')  

will fail, because jQuery objects are the heirs to the property only from their prototype.

I discourage using the constructor property for typed checks in JavaScript - it can work reliably for jQuery, but constructor As the object has only one asset, the prototype property of the constructor function is on time, there are several ways to mess with these tests ...


As a side note:

In JQuery, only obj & amp; Amp; Obj.jquery . It does not even use the example instead, instead of typing it typeof , duck-typing and toString.call () Uses a combination, where instanceof may fail.

In addition, hasonproperty () is never used. I'm not sure what this says about the quality of the jQuery library's code;)


Comments