检查object是否是jQuery对象 [英] Check if object is a jQuery object
问题描述
有没有快速检查对象是jQuery对象还是本机JavaScript对象的方法?
Is there a fast way of checking if an object is a jQuery object or a native JavaScript object?
示例:
var o = {};
var e = $('#element');
function doStuff(o) {
if (o.selector) {
console.log('object is jQuery');
}
}
doStuff(o);
doStuff(e);
显然,上面的代码有效,但不安全。您可以将选择键添加到 o
对象并获得相同的结果。有没有更好的方法来确保对象实际上是一个jQuery对象?
obviously, the code above works but it's not safe. You could potentially add a selector key to the o
object and get the same result. Is there a better way of making sure that the object actually is a jQuery object?
符合的东西(typeof obj =='jquery' )
推荐答案
您可以使用 instanceof
operator:
You can use the instanceof
operator:
obj instanceof jQuery
说明: jQuery
函数(又名 $
)实现为构造函数。构造函数将使用 new
前缀进行调用。
Explanation: the jQuery
function (aka $
) is implemented as a constructor function. Constructor functions are to be called with the new
prefix.
当您调用 $( foo)
,内部jQuery将其转换为 new jQuery(foo)
1 。 JavaScript继续在构造函数中初始化 this
,指向 jQuery
的新实例,将其属性设置为找到的属性在 jQuery.prototype
(又名 jQuery.fn
)。因此,你得到一个 new
对象,其中 instanceof jQuery
是 true
。
When you call $(foo)
, internally jQuery translates this to new jQuery(foo)
1. JavaScript proceeds to initialize this
inside the constructor function to point to a new instance of jQuery
, setting it's properties to those found on jQuery.prototype
(aka jQuery.fn
). Thus, you get a new
object where instanceof jQuery
is true
.
1 它实际上是新的jQuery。 prototype.init(foo)
:构造函数逻辑已被卸载到另一个名为 init
的构造函数,但概念是相同的。
1It's actually new jQuery.prototype.init(foo)
: the constructor logic has been offloaded to another constructor function called init
, but the concept is the same.
这篇关于检查object是否是jQuery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!