是否有一种快速的方法来检查一个对象是jQuery对象还是原生JavaScript对象?

例子:

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

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

doStuff(o);
doStuff(e);

显然,上面的代码可以工作,但并不安全。你可以给o对象添加一个选择器键并得到相同的结果。是否有更好的方法来确保对象实际上是一个jQuery对象?

(typeof obj == 'jquery')


当前回答

签出instanceof操作符。

var isJqueryObject = obj instanceof jQuery

其他回答

你也可以像下面描述的那样使用.jquery属性:http://api.jquery.com/jquery-2/

var a = { what: "A regular JS object" },
b = $('body');

if ( a.jquery ) { // falsy, since it's undefined
    alert(' a is a jQuery object! ');    
}

if ( b.jquery ) { // truthy, since it's a string
    alert(' b is a jQuery object! ');
}

对于那些想要在没有安装jQuery的情况下知道一个对象是否是jQuery对象的人来说,下面的代码片段应该可以完成工作:

function isJQuery(obj) {
  // All jQuery objects have an attribute that contains the jQuery version.
  return typeof obj === "object" && obj != null && obj.jquery != null;
}

你可以使用instanceof操作符:

if (obj instanceof jQuery){
    console.log('object is jQuery');
}

说明:jQuery函数(又名$)是作为构造函数实现的。构造函数将使用新前缀调用。

当调用$(foo)时,jQuery内部会将其转换为新的jQuery(foo)1。JavaScript继续在构造函数中初始化它,以指向一个新的jQuery实例,并将它的属性设置为jQuery上的属性。prototype(又名jQuery.fn)。因此,您将得到一个新对象,其中instanceof jQuery为真。


它实际上是新的jQuery.prototype.init(foo):构造函数逻辑已经被卸载给另一个构造函数init,但概念是一样的。

检查对象实例的最佳方法是通过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));
}

让我们看一看:逻辑运算符和真/假

但是,在jQuery中还有一种检查对象的方法。

jQuery.type(a); //this returns type of variable.

我已经做出了例子来理解事情,jsfiddle链接