检查对象实例的最佳方法是通过instanceof操作符或isPrototypeOf()方法检查对象的原型是否在另一个对象的原型链中。
obj instanceof jQuery;
jQuery.prototype.isPrototypeOf(obj);
但有时在文档上有多个jQuery实例的情况下可能会失败。正如@Georgiy Ivankin提到的:
如果我有$在我当前的命名空间指向query2,我有一个对象从外部命名空间(其中$是jQuery1),那么我没有办法使用instanceof检查该对象是否是jQuery对象
克服这个问题的一种方法是在闭包或IIFE中对jQuery对象进行别名化
//aliases jQuery as $
(function($, undefined) {
/*... your code */
console.log(obj instanceof $);
console.log($.prototype.isPrototypeOf(obj));
/*... your code */
}(jQuery1));
//imports jQuery1
解决这个问题的另一种方法是在obj中查询jquery属性
'jquery' in obj
但是,如果您尝试使用原语值执行该检查,则会抛出错误,因此您可以通过确保obj是Object来修改前面的检查
'jquery' in Object(obj)
虽然前面的方法不是最安全的(你可以在对象中创建'jquery'属性),但我们可以通过使用这两种方法来改进验证:
if (obj instanceof jQuery || 'jquery' in Object(obj)) { }
这里的问题是,任何对象都可以将属性jquery定义为own,因此更好的方法是在原型中询问,并确保对象不是null或未定义的
if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }
由于强制,当obj是任何一个假值(null, undefined, false, 0, "")时,if语句将通过计算&&运算符短路,然后继续执行其他验证。
最后我们可以写一个效用函数:
function isjQuery(obj) {
return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}
让我们看一看:逻辑运算符和真/假