pimvdb
pimvdb

Reputation: 154898

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:

What is the difference, and what is preferred?

Upvotes: 5

Views: 1260

Answers (2)

JAAulde
JAAulde

Reputation: 19560

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.

Upvotes: 6

Tgr
Tgr

Reputation: 28200

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

Upvotes: 1

Related Questions