jQueryPlugin: return this vs return this.each()
Two things:
- Your examples are flawed in that they do exactly the same thing to each element.
- The real issue isn't
return this
versusreturn this.each
, the issue isthis
versusthis.each
.
For (1), consider the difference between this plugin:
(function($) {
$.fn.mangle = function(options) {
this.append(' - ' + this.data('x'));
return this;
};
})(jQuery);
Demo: http://jsfiddle.net/ambiguous/eyHeu/
And this plugin:
(function($) {
$.fn.mangle = function(options) {
return this.each(function() {
$(this).append(' - ' + $(this).data('x'));
});
};
})(jQuery);
Demo: http://jsfiddle.net/ambiguous/5dMMH/
So you see, you need to use this.each
if you need to treat the individual elements in the this
set differently. You would have similar effects if your plugin had to attach element-specific data to each element: if you didn't use each
then you'd end up attaching the exact same piece of data to all of the elements inside this
and that would just leave you confused about why information is bleeding all over the place.
For (2), it doesn't matter if you return this
or return this.each(...
since x.each(...)
returns x
anyway.