Javascript Chaining Pattern

I've always been intrigued by the chaining pattern that jQuery implements. It's such an elegant way to present an API: it's both concise, and readable.

//Example
$('.foo')
    .addClass('bar')
    .html('hello world')
    .fadeIn('slow');

It turns out that the fundamentals of this pattern isn't that complicated.

(I'll update you guys again when I actually try to implement it into my code... hah)

The main key to the chaining pattern involves returning the object at the end of each method using return this, which allows additional methods to be called on the object again.

I've written a short codepen to play around with this chaining pattern.

See the Pen JavaScript Chaining Pattern by Duncan (@duncanleung) on CodePen.

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!