how does jquery chaining work?

isJustMe picture isJustMe · Sep 19, 2011 · Viewed 28.1k times · Source

I am not asking what is the appropriate syntax for chaining, I know it could be something like:

$('myDiv').removeClass('off').addClass('on');

However I'm really curious to understand the inner working of it, as far as I know chaining is one of the advantages against other famous frameworks but this us to much abstraction for a novice programer like me, I'm sure there is someone out there that can provide me with a explanation that allows me to understand how chaining works.

Thanks!

Answer

user113716 picture user113716 · Sep 19, 2011

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/