JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let us look at the previous articles of the series:
Chaining
This technique got / retrieved popularity from jQuery. We write series of statements one after the other like a chain,
ex,
- $("#h1").text("Change text").css("color", "red");
- Another example of chaining while working with strings:
- var s="hello";
- s.substring(0,4).replace('h','H');
The Chaining Method is also known as Cascading, because it repeatedly calls one method on an object forming a chain/continuous line of code.
Chaining methods
Ques: What is returned if there is no return statement in method?
Ans: undefined
Ques: How is chaining implemented?
Ans: When a method returns this; the entire object is returned & it is passed to next method and it is called chaining. Example,
- var games = function()
- {
- this.name = '';
- }
- games.prototype.getName = function()
- {
- this.name = 'Age of Empire';
- return this;
- }
- games.prototype.setName = function(n)
- {
- this.name = n;
- }
-
- var g = new games();
- g.getName().setName('Angry Birds');
- console.log(g.name);
We’ve created getName method which returns this and implemented chaining.
Advantages - Code is more maintainable, simple, lean
- It is easy to read chaining code
Simplify code after chaining
Use case: Let usthe examine traditional way to program things. We have a problem to sort string below:
Approach 1
- var vehicles = "Bike|Car|Jeep|Bicycle";
- vehicles = vehicles.split( "|" );
- vehicles = vehicles.sort();
- vehicles = vehicles.join( "," );
- console.log(vehicles);
Output: Bicycle, Bike, Car, Jeep
Approach 2: - var vehicles = "Bike|Car|Jeep|Bicycle";
- vehicles = vehicles.split('|').sort().join(',');
- console.log(vehicles);
Output: Bicycle, Bike, Car, Jeep
Please share your feedback / comments.