how does jquery chaining work?

If you have an object with certain methods, if each method returns an object with methods, you can simply call a method from the object returned.

var obj = {   // every method returns obj---------v
    first: function() { alert('first');   return obj; },
    second: function() { alert('second'); return obj; },
    third: function() { alert('third');   return obj; }
}

obj.first().second().third();

DEMO: http://jsfiddle.net/5kkCh/


All that it is doing is returning a reference to this when the method finishes. Take this simple object for example:

 var sampleObj = function()
 {
 };

 sampleObj.prototype.Foo = function()
 {
     return this;
 };

You could chain these calls all day because you return a reference to this:

var obj = new sampleObj();
obj.Foo().Foo().Foo().Foo() // and so on

jQuery simply performs an operation, then returns this.


Basically the first function call $('myDiv') returns a jQuery object, then each subsequent call returns the same one.

Loosely,

var $ = function(selector) {
   return new jQuery(selector);
};

jQuery.prototype.removeClass = function(className) {
   // magic
   return this;
}