Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - 检查object是否是jQuery对象(Check if object is a jQuery object)

Is there a fast way of checking if an object is a jQuery object or a native JavaScript object?(有没有快速检查对象是jQuery对象还是本机JavaScript对象的方法?)

example:(例:) var o = {}; var e = $('#element'); function doStuff(o) { if (o.selector) { console.log('object is jQuery'); } } doStuff(o); doStuff(e); 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.(您可以将选择键添加到o对象并获得相同的结果。) Is there a better way of making sure that the object actually is a jQuery object?(有没有更好的方法来确保对象实际上是一个jQuery对象?) Something in line with (typeof obj == 'jquery')(符合的东西(typeof obj == 'jquery'))   ask by David Hellsing translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the instanceof operator:(您可以使用instanceof运算符:)

obj instanceof jQuery Explanation : the jQuery function (aka $ ) is implemented as a constructor function .(说明jQuery函数(又名$ )是作为构造函数实现的 。) Constructor functions are to be called with the new prefix.(使用new前缀调用构造函数。) When you call $(foo) , internally jQuery translates this to new jQuery(foo) 1 .(当你调用$(foo) ,内部jQuery会将其转换为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 ).(JavaScript继续在构造函数内初始化this以指向jQuery的新实例,将其属性设置为jQuery.prototype (aka jQuery.fn )上的属性。) Thus, you get a new object where instanceof jQuery is true .(因此,您将获得一个new对象,其中instanceof jQuerytrue 。) 1 It'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.(1 它实际上是new jQuery.prototype.init(foo) :构造函数逻辑已被卸载到另一个名为init构造函数,但概念是相同的。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...