Share on facebook
Facebook
Share on twitter
Twitter

JavaScript Like a 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 it, and cross-browser performance implications. 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 instance is a great example of what a fluent API allows you to do: 1 2 3 4 $(‘

‘) .html(“Fluent API are cool!”) .addClass(“header”) .appendTo(“body”); Fluent API lets you chain function calls by returning this object. We can easily create a fluent API like this: 1 2 3 4 5 6 7 8 9 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 (reference to current instance in this case) to allow the chain to continue. If […]

X