检查对象实例的最佳方法是通过 instanceof 运算符 或使用方法 isPrototypeOf() 检查对象的原型是否在另一个对象的原型链中。
obj instanceof jQuery;
jQuery.prototype.isPrototypeOf(obj);
但有时它可能会在文档上有多个 jQuery 实例的情况下失败。正如@Georgiy Ivankin 所说:
如果我在当前命名空间中有$ 指向jQuery2,并且我有一个来自外部命名空间的对象(其中$ 是jQuery1),那么我无法使用instanceof检查该对象是否为jQuery 对象
解决该问题的一种方法是在 closure 或 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定义为自己的,所以更好的方法是在原型中询问,并确保对象不是null或undefined
if (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery)) { }
由于强制,当obj 是任何falsy 时,if 语句将通过评估&& 运算符来短路值(null、undefined、false、0、""),然后继续执行其他验证。
终于可以写一个效用函数了:
function isjQuery(obj) {
return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}
我们来看看:Logical Operators and truthy / falsy