Function chaining in Javascript
In this, I am going to explain about function chaining in Javascript. Function chaining is nothing but calling function one by one in a single line instead of calling a function line by line.
Let me explain to you with an example.
var obj = function() {
this.i = 0;
this.add = function(i) {
this.i += i;
return this;
};
this.substract = function(i) {
this.i -= i;
return this
};
this.print = function() {
console.log(this.i);
};
}
var x = new obj();
// we can call the functions like the normal way
x.add(2);
x.substract(1);
x.print(); // This will give normal output
//if we try to call them by using the method chaining
x.add(2).substract(1).print(); // This will print undefined
The above example prints undefined because the reason is when we are doing x.add() it is not returning anything.
Solution for this is if we try to return the entire object so that it will store the next functions.
Let me show you an example:
var obj = function() {
this.i = 0;
this.add = function(i) {
this.i += i;
return this;
};
this.substract = function(i) {
this.i -= i;
return this
};
this.print = function() {
console.log(this.i);
};
}
var x = new obj();
//if we try to call them by using the method chaining
x.add(2).substract(1).print(); // This will print the expected output
So by returning entire object we achieved method chaining.