Usually, the best convention to write a plugin is something like this :
$.fn.pluginName = function(){
// return the same object to preserve chainability
// and also apply the plugin's functionality to all the
// dom elements in this jquery collection
return this.each(function(i,el){
// do whatever you want with $(el)
});
};
If you are writing a plugin that returns a value instead of manipulating in some way the current object (say like width works), you should return that value instead of the current object reference (this) :
$.fn.maxWidth = function(){
var max = 0;
this.each(function(i,el){
var w = $(el).width();
if(w > max)
max = w;
});
return max;
};
If you want to give the user the possibility to access & modify your plugin functionality, you should definitely preserve chainability (I mean to return this and not some other object containing you plugin's api) and expose the plugin's API to the user through the jQuery element's data method.
Here's an example. Lets say that we're making a video player jquery plugin. We want to preserve chainability, but still be able to access the core functions of this plugin.
The right way to do this would be something like this :
$.fn.videoPlayer = function(){
var api = {
play : function(){/*...*/},
pause : function(){/*...*/},
stop : function(){/*...*/}
};
return this.each(function(i,el){
$(el).data('videoPlayerApi',api);
});
};
An usage example which demonstrates my point :
$('video')
// initialising the plugin
.videoPlayer()
// the return value is the original jQuery object,
// so we can still call jQuery methods on it
.css('opacity',1)
// select the first video
.eq(0)
// access the first video's plugin api
.data('videoPlayerApi')
// start only the first video
.start();