Explain method chaining in JavaScript by implementing a calculator that performs the basic actions like add, subtract, divide, and multiply.
Example
calculator.add(10).subtract(2).divide(2).multiply(5); console.log(calculator.total); //20
Method chaining is an object-oriented paradigm, in which the methods usually share the same reference, which in JavaScript is done by sharing this (current context) from each method.
We are going to see the two different implementations of method chaining.
1. Using objects.
2. With functions.
Using objects
Methods inside the object can refer to the current object using this keyword, thus we can use the same to perform our operations and return them so that they can be shared around the chain.
const calculator = { total: 0, add: function(val){ this.total += val; return this; }, subtract: function(val){ this.total -= val; return this; }, divide: function(val){ this.total /= val; return this; }, multiply: function(val){ this.total *= val; return this; } };
Input: calculator.add(10).subtract(2).divide(2).multiply(5); console.log(calculator.total); Output: 20
The problem with objects is that we cannot create a new instance of them. But it can be solved using functions.
Method chaining with functions
const CALC = function(){ this.total = 0; this.add = (val) => { this.total += val; return this; } this.subtract = (val) => { this.total -= val; return this; } this.multiply = (val) => { this.total *= val; return this; } this.divide = (val) => { this.total /= val; return this; } this.value = () => this.total; }
Input: const calculator = new CALC(); calculator.add(10).subtract(2).divide(2).multiply(5); console.log(calculator.total); Output: 20