views:

72

answers:

2

Hello,

In jQuery plugins, every time we return an object of jQuery, like

$.fn.Myplugin = function() {
      return this.each(function() { //do some stuff });
});

My doubt is, why do we actually return an object of jQuery and where are we going to use this returned object

Though I don't return any jQuery object in my function(plugin), I still get the same result just as in returning an object

someone please explain my doubt,

Thanks for sparing your time, Have a Good Day !

+10  A: 

The jQuery object is returned so we can do method chaining:

$('#somelement').doSomething().doAnotherThing().doOneMoreThing();

If you don't return it from one of your plugin methods, there's no more jQuery object to work with so subsequent calls will result in an error.

BoltClock
Thanks for clearing my doubt
Ninja Dude
+2  A: 

All jQuery methods return you jQuery Object so that the set of results returned can further be used to perform other operations this is also called chaining. This is done for tersness in the code. Its easy to code (atleast for me) and prevents me writing big loops.

sushil bharwani
Thank you sushil !
Ninja Dude