Skip to content

How to chain methods of an Object in JavaScript

Last updated on February 24, 2020

This post will help you to get a grasp of one simple concept of method chaining in JavaScript.

We have used this kind of pattern with most of the JavaScript-based libraries out there, for example, JQuery, SVG based charting library D3.js and list go on.

Here I will cover you how this gets implemented, so that we can also get benefit from this pattern and use this in our projects.

As usually, I will walk-through with the coding snippet that will get you an easy understanding.

function User(options) {
  if(!(this instanceof User)) {
    return new User();
  }
  var sessionCount = 0;
  this.name = options.name || '';
  this.emailId = options.emailId || '';

  this.increaseSessionCount = function(value) {
     sessionCount = sessionCount + 1;
     
     return this; (A)
  };

  this.getSessionCount = function() {
     return sessionCount;
  }
}

Consider from the above code, we have an User function constructor where we expect parameters and exposes increaseSessionCount & getSessionCount methods.

The above is the result of executing our User object.
admin.increaseSessionCount().getSessionCount()represents method chaining. But when you call getSessionCount()method it simply returns the calculated value of sessionCount variable.

In short, Just by simply returning this keyword from our method, we will be able to easily chain the methods but we cannot do like admin.getSessionCount().increaseSessionCount() which throws an error saying Uncaught TypeError.

That’s it for today, I hope you understand this pattern in an easy way. You can always shoot out questions in comments section. I will be happy to help you out.

Published inJavaScriptReact