JQuery: return this

In jQuery plugins every time we return a jQuery object like

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

I doubt why we really return the jQuery object and where we will use this returned object

Although I do not return the jQuery object to my function ( plugin ), I still get the same result as when returning the object

someone please explain my doubts

Thank you for sparing your time, having a good day!

+4
source share
2 answers

The jQuery object is returned, so we can execute a chain of methods:

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

If you do not return it from one of your plugin methods, the jQuery object will no longer work, so subsequent calls will result in an error.

+14
source

All jQuery methods return a jQuery object to you, so the set of returned results can be additionally used to perform other operations, this is also called a chain. This is done for code in code. It is easy to code (at least for me) and prevents me from writing large loops.

+3
source

Source: https://habr.com/ru/post/1316006/


All Articles