Friday, 8 December 2017

javascript - Check if object is a jQuery object

itemprop="text">

Is there a fast way of checking if an
object is a jQuery object or a native JavaScript
object?



example:




var
o = {};
var e = $('#element');

function doStuff(o)
{
if (o.selector) {
console.log('object is jQuery');

}
}


doStuff(o);
doStuff(e);


obviously,
the code above works but it's not safe. You could potentially add a selector key to the
o object and get the same result. Is there a better way of
making sure that the object actually is a jQuery
object?



Something in line with
(typeof obj == 'jquery')



Answer




You can use the href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Instanceof_Operator"
rel="noreferrer">instanceof
operator:




obj
instanceof
jQuery


Explanation:
the jQuery function (aka $) is
implemented as a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Using_a_constructor_function"
rel="noreferrer">constructor function. Constructor functions are to be
called with the new
prefix.



When you call
$(foo), internally jQuery translates this to new
jQuery(foo)
1. JavaScript proceeds to initialize
this inside the constructor function to point to a new instance
of jQuery, setting it's properties to those found on
jQuery.prototype (aka jQuery.fn).
Thus, you get a new object where instanceof
jQuery
is
true.



/>

1It's actually
new jQuery.prototype.init(foo): the constructor logic has been
offloaded to another constructor function called init, but the
concept is the same.




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...