Method chaining is a mechanism of calling a method on another method of the same object. There are different reasons for method chaining for different people. One of the major reasons for chaining methods is to ensure a cleaner and more readable code. Let's consider an example below:
var recipeObj = new Recipe();
recipeObj.addIngredient('salt');
recipeObj.addIngredient('pepper');
recipeObj.getIngredients()
With method chaining, the code snippet above can be refactored to:
var recipeObj = new Recipe();
recipeObj
.addIngredient('salt')
.addIngredient('pepper')
.getIngredients();
Looking at both snippets above, one would agree that the second is cleaner than the first.
What makes method chaining possible?
What makes the method chaining possible is the this
keyword. In JavaScript, the this
keyword refers to the current object in which it is called. Hence, when a method returns this
, it simply returns an instance of the object in which it is returned. Since the returned value is an object instance, it is, therefore, possible for other methods of the object to be called on the returned value which is its instance.
Method Chaining Example in ES5
function Recipe() {
this.ingredients = [];
}
Recipe.prototype.addIngredient = function (ingredient) {
this.ingredients.push(ingredient);
return this; // this makes chaining possible
}
Recipe.prototype.getIngredients = function () {
if (!this.ingredients.length) {
console.log('There is no ingredient in this recipe');
} else {
console.log(this.ingredients.toString());
}
}
var recipeObj = new Recipe();
recipeObj
.addIngredient('salt')
.addIngredient('pepper')
.addIngredient('maggi')
.getIngredients()
//salt,pepper,maggi
Method Chaining Example in ES6
class RecipeClass {
constructor() {
this.ingredients = [];
}
addIngredient = (ingredient) => {
this.ingredients.push(ingredient);
return this;
}
getIngredients = () => {
if (!this.ingredients.length) {
console.log('There is no ingredient in this recipe');
} else {
console.log(this.ingredients.toString());
}
}
}
const recipeObj2 = new RecipeClass();
recipeObj2
.addIngredient('garlic')
.addIngredient('pepper')
.addIngredient('maggi')
.getIngredients()
//garlic,pepper,maggi
Conclusion
In this short article, I explained the concept of method chaining in Javascript and demonstrated how it can be achieved using the this
keyword. You can give it a try. ✌️