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!
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.
DEMO: http://jsfiddle.net/5kkCh/
The point is that a function must evaluate to the "parent" function. So e.g.
has to evaluate to:
so that you can call another function on
foo()
. To do this, you canreturn this
:Then,
And because of this:
So because
something.bar()
evaluates tosomething
, you can immediately call the second function in one go.One of the way to chaining, check demo .
each jQuery function returns an instance of the jQuery class, which can then have methods called on it. you could break it down, and this code would have the same effect.
Here is an example of conditional callback chaining, like is used on the
$.ajax
jQuery function.In chaining parent function/method returns an object which is then used by the child function/method, and things go on such a way. In short the
jQuery
or$
returns itself (an object) which allows the chaining.It is the same mechanism below
It looks like this if it is done with chaining