Method Chaining in JavaScript

JavascriptFront End TechnologyObject Oriented Programming

Chaining Methods, also known as Cascading, means repeatedly calling one method after another on an object, in one continuous line of code. Let us look at an example where method chaining can help us avoid repetition.

Example

Take the following class car for example -

class Car {
   constructor() {
      this.wheels = 4
      this.doors = 4
      this.topSpeed = 100
      this.feulCapacity = "400 Litres"
   }
   setWheels(w) {
      this.wheels = w
   }
   setDoors(d) {
      this.doors = d
   }
   setTopSpeed(t) {
      this.topSpeed = t
   }
   setFeulCapacity(fc) {
      this.feulCapacity = fc
   }
   displayCarProps() {
      console.log(`Your car has ${this.wheels} wheels,\
      ${this.doors} doors with a top speed of ${this.topSpeed}\
      and feul capacity of ${this.feulCapacity}`)
   }
}
let sportsCar = new Car();
sportsCar.setDoors(2)
sportsCar.setTopSpeed(250)
sportsCar.setFeulCapacity("600 Litres")
sportsCar.displayCarProps()

Output

Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 

See how many times sportsCar is unnecessarily repeated? We can get rid of it by using method chaining. To do so, instead of letting the setters just setting the value, return this at the end. This will allow us to perform operations on the object. After making this change, our code looks like −

class Car {
   constructor() {
      this.wheels = 4
      this.doors = 4
      this.topSpeed = 100
      this.feulCapacity = "400 Litres"
   }
   setWheels(w) {
      this.wheels = w;
      return this;
   }
   setDoors(d) {
      this.doors = d;
      return this;
   }
   setTopSpeed(t) {
      this.topSpeed = t;
      return this;
   }
   setFeulCapacity(fc) {
      this.feulCapacity = fc;
      return this;
   }
   displayCarProps() {
      console.log(`Your car has ${this.wheels} wheels,\
      ${this.doors} doors with a top speed of ${this.topSpeed}\
      and feul capacity of ${this.feulCapacity}`)
   }
}

Now we can change the part where we create the car object with the more readable and less repeating code −

Example

let sportsCar = new Car()
   .setDoors(2)
   .setTopSpeed(250)
   .setFeulCapacity("600 Litres")
   .displayCarProps()

Output

Your car has 4 wheels,2 doors with a top speed of 250and feul capacity of 600 Litres 

Method chaining is also called fluent interface as it allows to operate on the object through methods without breaking the flow again and again by repeating the object.

raja
Published on 17-Sep-2019 08:44:41
Advertisements