When creating a jQuery plugin, what should be 开发者_如何学JAVAreturned 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?
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
精彩评论