What is method chaining in JavaScript?

Problem

A good programming practice is to write a number of functions​/methods to deal with individual actions; writing just one function to cater to all of the actions is a terrible practice.

However, sticking to the good practice takes a toll on the readability and understandability of the code because defining a separate function for each action means that the output of one function/method is the input of another. This results in the code looking as follows:


const my_object = new MyClass()
my_object.method1(
    my_object.method2(
         my_object.method3()
    )
)

Note: the flow of data is actually from the inner function to the outer function.

This makes the code understandability even worse since, now, the function needs to be nested in reverse order.

This is where method chaining comes in.

Method chaining

Method chaining uses the this keyword in the object’s class to access its methods.

this is the current object instance, therefore, it has access to all the methods defined on the instance as well as access to the prototype chain. method1() of MyClass can be accessed using this.method1().

Let’s rewrite the above code using method chaining:

class method_chaining {
method1() {
console.log('This is method1');
return this;
}
method2() {
console.log('This is method2');
return this;
}
method3() {
console.log('This is method3');
return this;
}
}
const method_chaining_obj = new method_chaining()
method_chaining_obj
.method1()
.method2()
.method3();

Take a look at lines 192219-22. The functions are nested in the same order they’re executed in instead of in reverse. The output of one method becomes the input of the method that follows. This approach makes​ the code easier to understand while eliminating the need to worry about closing parentheses and brackets.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved