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 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

Popular posts from this blog

What is MQTT protocol & its use

What the hack is Call, bind & apply

What is Provider in Angular Js?