dcgenjin
dcgenjin

Reputation: 1108

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

Upvotes: 1

Views: 107

Answers (1)

danbal
danbal

Reputation: 1531

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.

Upvotes: 2

Related Questions