检查对象实例的最佳方法是通过instanceof运算符或使用isPrototypeOf()方法检查对象的原型是否在另一个对象的原型链中。
obj instanceof jQuery;
jQuery.prototype.isPrototypeOf(obj);
但有时它可能会在文档上有多个 jQuery 实例的情况下失败。正如@Georgiy Ivankin 提到的:
如果我$
在我当前的命名空间中指向jQuery2
并且我有一个来自外部命名空间(where $
is jQuery1
)的对象,那么我无法instanceof
用来检查该对象是否是一个jQuery
对象
解决该问题的一种方法是在闭包或IIFE 中为 jQuery 对象添加别名
(function($, undefined) {
console.log(obj instanceof $);
console.log($.prototype.isPrototypeOf(obj));
}(jQuery1));
其他与解决这一问题的方法是通过询问jquery
物业obj
'jquery' in obj
但是,如果您尝试使用原始值执行该检查,则会引发错误,因此您可以通过确保obj
是一个Object
'jquery' in Object(obj)
尽管前一种方法不是最安全的(您可以'jquery'
在对象中创建属性),但我们可以通过使用这两种方法来改进验证:
if (obj instanceof jQuery || 'jquery' in Object(obj)) { }
这里的问题是任何对象都可以将属性定义jquery
为自己的,因此更好的方法是在原型中询问,并确保该对象不是null
或undefined
if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }
由于coercion,当是任何假值 ( , , , , ) 时,if
语句将通过评估&&
运算符来短路,然后继续执行其他验证。obj
null
undefined
false
0
""
最后我们可以写一个效用函数:
function isjQuery(obj) {
return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}
我们来看看:逻辑运算符和真/假