检查对象是否为jQuery对象

JavaScript

MandyL

2020-03-12

有没有一种快速的方法来检查对象是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')

第895篇《检查对象是否为jQuery对象》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
阿飞泡芙 2020.03.12
var elArray = [];
var elObjeto = {};

elArray.constructor == Array //TRUE
elArray.constructor == Object//TALSE

elObjeto.constructor == Array//FALSE
elObjeto.constructor == Object//TRUE
LEYJim 2020.03.12

You can check if the object is produced by JQuery with the jquery property:

myObject.jquery // 3.3.1

=> return the number of the JQuery version if the object produced by JQuery. => otherwise, it returns undefined

泡芙卡卡西 2020.03.12
return el instanceof jQuery ? el.size() > 0 : (el && el.tagName);
entaseven 2020.03.12

对于那些想知道一个对象是否是一个jQuery对象而不安装jQuery的人,以下代码片段应该可以完成工作:

function isJQuery(obj) {
  // Each jquery object has a "jquery" attribute that contains the version of the lib.
  return typeof obj === "object" && obj && obj["jquery"];
}
Pro西门 2020.03.12

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

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

我做了例子来了解事物,jsfiddle链接

达蒙十三 2020.03.12

检出instanceof运算子。

var isJqueryObject = obj instanceof jQuery
路易番长 2020.03.12

您可以使用instanceof运算符:

obj instanceof jQuery

说明:该jQuery函数(又名$)被实现为构造函数构造函数将以new前缀调用

调用时$(foo),内部jQuery将此转换为new jQuery(foo)1JavaScript继续this在构造函数内部进行初始化,以指向的新实例jQuery,并将其属性设置为jQuery.prototype(aka jQuery.fn上的属性因此,您得到的new对象instanceof jQuerytrue


1 实际上是new jQuery.prototype.init(foo):构造函数逻辑已被卸载到另一个名为的构造函数中init,但是概念是相同的。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android