Introduction
It is really easy to maintain a small concise code in JavaScript. If there are multiple actions needed to be performed on an object, then the developer needs to write many lines of code to call the functions. In that case, it will be difficult for other developers to understand and maintain in the future. It would be really easy if you can call subsequent actions on an object one by one.
There are some jQuery function chainings available that perform the chaining task seamlessly.
- $("div").addClass("greenbackground").removeClass("className");
Let's learn to create this chain function for a custom object in JavaScript.
Example
- var class1 = function() {
- this.result = 0;
- this.add = function(input) {
- this.result += input;
- return this;
- }
- this.substract = function(input) {
- this.result -= input;
- return this;
- }
- this.print = function() {
- console.log(this.result);
- }
- };
- var object = new class1();
- object.add(3).substract(2).print();
Explanations
In the above example, I am creating a constructor - "class1". It has a variable result which is assigned as 0 at the time of initialization. This constructor also contains 3 methods.
- add - which adds the input to the existing value.
- substract - which subtracts the given input from the existing value.
- Print - It prints the values after the operation.
Without Function chaining, if we need to do multiple operations, then we need to write multiple lines of code.
- object.add(3);
- object.subtract(2);
- object.print();
For a simple operation, only 3 lines of code are needed here. To avoid that, the chaining concept is implemented.
To provide function chaining, each function needs to return the object so that the next function can be implemented on the output of the first function, like in the above example.
is present in both add and subtract functions. But for printing, we don't need to add this line as it will always be the last function to be called in a function chain to print the output. By returning the object after the evaluation, the function provides scope for chaining. Like here, add function is open for chaining by returning the object and same is with subtracting function to implement function chaining developer needs to create an object like
- var object = new class1();
It will ensure that the "object" will inherit all the properties of the constructor (class1 here). It ensures the smooth functioning of function chaining. Function chaining can also be implemented with the closure in JavaScript
Conclusion
Function chaining is a nice concept provided in JavaScript. It encourages developers to create highly maintainable code. Please provide your feedback in the comments. This will encourage me to improve myself.