The best way to check the instance of an object is through instanceof operator or with the method isPrototypeOf() which inspects if the prototype of an object is in another object's prototype chain.
obj instanceof jQuery;
jQuery.prototype.isPrototypeOf(obj);
But sometimes it might fail in the case of multiple jQuery instances on a document. As @Georgiy Ivankin mentioned:
if I have
$
in my current namespace pointing tojQuery2
and I have an object from outer namespace (where$
isjQuery1
) then I have no way to useinstanceof
for checking if that object is ajQuery
object
One way to overcome that problem is by aliasing the jQuery object in a closure or IIFE
//aliases jQuery as $
(function($, undefined) {
/*... your code */
console.log(obj instanceof $);
console.log($.prototype.isPrototypeOf(obj));
/*... your code */
}(jQuery1));
//imports jQuery1
Other way to overcome that problem is by inquiring the jquery
property in obj
'jquery' in obj
However, if you try to perform that checking with primitive values, it will throw an error, so you can modify the previous checking by ensuring obj
to be an Object
'jquery' in Object(obj)
Although the previous way is not the safest (you can create the 'jquery'
property in an object), we can improve the validation by working with both approaches:
if (obj instanceof jQuery || 'jquery' in Object(obj)) { }
The problem here is that any object can define a property jquery
as own, so a better approach would be to ask in the prototype, and ensure that the object is not null
or undefined
if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }
Due to coercion, the if
statement will make short circuit by evaluating the &&
operator when obj
is any of the falsy values (null
, undefined
, false
, 0
, ""
), and then proceeds to perform the other validations.
Finally we can write an utility function:
function isjQuery(obj) {
return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}
Let's take a look at: Logical Operators and truthy / falsy
No comments:
Post a Comment