简体   繁体   中英

using this rather than $(this) in an .each() call

I've done quite a lot of reading this past day to get a deeper understanding of this vs. $(this) and how JS determines this as it interprets, but I still can't figure out one detail of a plugIn I'm analyzing to deepen my knowledge:

$.fn.plugInName = function(options) {
  return this.each(function() {
    new $.plugInName(this,options);
  });
};

Everything I've read indicates that although this.each() is used to call JQuery.prototype.each(), each object should be referred to as $(this) within the each() function, but the above uses regular ol' this, and I can't figure why. The $.plugInName declaration looks like this:

$.plugInName = function(el,options) {
  ...
}

Any insights anyone may have will be a big help.

EDIT: Here's the full source on GitHub

From MDN :

When a function is called as a method of an object, its this is set to the object the method is called on.

When you call something like

$('#myDiv').plugInName()

the function is called as a method of the jQuery object $('#myDiv') . So, in this case, this already refers to a jQuery object, thus we don't need the extra $() wrapper.

A common case when we do need $() is when binding events.

$('#myDiv').on('click', function(){
    alert('You clicked my div!');
});

The difference here is that the function is called not on $('#myDiv') , but the DOM element that it belongs to. So, here this is a DOM object, not a jQuery object.


Inside the callback function passed to each , this refers to the DOM element, it is not a jQuery object.. which is just what $.plugInName wants. It expects a DOM element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM