Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside a jQuery plugin, return 'this' or '$(this)'?

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?

like image 974
pimvdb Avatar asked Mar 26 '11 18:03

pimvdb


People also ask

What does $() return in jQuery?

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.

What is a jQuery plugin?

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.

Where do I put jQuery plugins?

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.


2 Answers

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.

like image 50
JAAulde Avatar answered Nov 02 '22 22:11

JAAulde


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
like image 41
Tgr Avatar answered Nov 02 '22 22:11

Tgr