Function Chaining in Javascript
What is Method Chaining?
Method chaining is a technique that can be used to simplify code in scenarios that involve calling multiple functions on the same object consecutively.
Let's write the
Below listed two examples with and without method chaining on our new class:
Kitten
class with the ability to chain methods.
// define the class
var Kitten = function() {
this.name = 'Garfield';
this.color = 'brown';
this.gender = 'male';
};
Kitten.prototype.setName = function(name) {
this.name = name;
return this;
};
Kitten.prototype.setColor = function(color) {
this.color = color;
return this;
};
Kitten.prototype.setGender = function(gender) {
this.gender = gender;
return this;
};
Kitten.prototype.save = function() {
console.log(
'saving ' + this.name + ', the ' +
this.color + ' ' + this.gender + ' kitten...'
);
// save to database here...
return this;
};
Below listed two examples with and without method chaining on our new class:
// WITHOUT CHAINING
var bob = new Kitten();
bob.setName('Bob');
bob.setColor('black');
bob.setGender('male');
bob.save();
// OUTPUT:
// > saving Bob, the black male kitten...
// WITH CHAINING
new Kitten()
.setName('Bob')
.setColor('black')
.setGender('male')
.save();
// OUTPUT:
// > saving Bob, the black male kitten...
By using method chaining we end up with much cleaner code that is easier to understand.
Comments
Post a Comment