When creating a jQuery plugin, what should be returned in a $.fn
function? Is it return this
or return $(this)
? Some of the websites I came across when searching use the former, whereas other websites use the latter:
return $(this)
:
http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx (tip 10)return this
:
http://devheart.org/articles/tutorial-creating-a-jquery-plugin/
What is the difference, and what is preferred?
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By extending the prototype object you enable all jQuery objects to inherit any methods that you add. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited.
How to use Plugins. To make a plug-in's methods available to us, we include plug-in file very similar to jQuery library file in the <head> of the document. We must ensure that it appears after the main jQuery source file, and before our custom JavaScript code.
Directly inside of a function which lives on $.fn
(the prototype of the jQuery constructor), this
refers to the jQuery collection instance on which the function is operating. Returning this
is proper. Wrapping it in $()
just adds unnecessary weight to your code.
See Context section of jQuery plugin authoring guidelines.
this
is the jQuery object on which your function has been invoked; $(this)
is a shallow copy of the object (another jQuery object, referring to the same DOM elements or whatever objects the original held). Normally, this
should be better because 1) creating a copy of the jQuery object takes a nontrivial amount of operations, 2) you don't usually change properties of the jQuery object.
Now if you do change properties then the two behave differently:
var foo = $('#id');
var bar = $(foo);
foo.baz = 1;
bar.baz; // undefined
and in that case returning $(this)
might make more sense. For example, jQuery's own add
function does something like this internally:
var next = $(this);
// add parameter to next
return next;
so when you add an element to a jQuery object, it does not modify the original:
var foo = $('html');
var bar = foo.add('body');
bar.length; // 2
foo.length; // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With