JavaScript like a Boss: Understanding Fluent APIs

Originally published at: http://www.sitepoint.com/javascript-like-boss-understanding-fluent-apis/

While designing Babylon.js v2.0 (a library for building 3D on the web), I recently found myself wishing that more APIs were fluent – that is, I wish the community could more easily read, understand, and build upon the work while spending less time in the tech docs. In this tutorial, I’ll walk through Fluent APIs – what to consider, how to write them, and cross-browser performance implications.

fluent01 - should i

What Makes an API Fluent?

A fluent API, as stated by this Wikipedia article, is an implementation of an object-oriented API that aims to provide for more readable code. jQuery, for example, is a great example of what a fluent API allows you to do:

$('<div></div>')
     .html("Fluent API are cool!")
     .addClass("header")
     .appendTo("body");

A fluent API lets you chain function calls by returning the this object.

We can easily create a fluent API like this:

var MyClass = function(a) {
    this.a = a;
}

MyClass.prototype.foo = function(b) {
    // Do some complex work   
    this.a += Math.cos(b);
    return this;
}

As you can see, the trick is just about returning the this object (a reference to the current instance in this case) to allow the chain to continue.

If you are not aware of how the this keyword works in JavaScript, I recommend reading this great article by Mike West.

We can then chain calls:

var obj = new MyClass(5);
obj.foo(1).foo(2).foo(3);

Before trying to do the same with Babylon.js, I wanted to be sure that this would not generate some performance issues.

So I did a benchmark!

Continue reading this article on SitePoint

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.