Alex Rivera | Logout

How do object or method chaining work in jQuery?

Asked 2011-09-19T18:09:44.823
59

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

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

As far as I know chaining is one of the advantages against other famous frameworks. Can someone explain to me how chaining works here?

Edit
Report

1 Answer

74

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/

answered 2011-09-19T18:12:18.663

Your Answer