User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2018 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper Method Chaining in JavaScript

Method chaining is a technique that can be used to simplify code in
scenarios that involve calling multiple functions on the same object
consecutively. This is an example of how you can use method chaining
when using jQuery.

 

Example :
$('#my-div').css('background', 'blue').height(100).fadeIn(200);

// often broken to multiple lines:
$('#my-div')
  .css('background', 'blue')
  .height(100)
  .fadeIn(200);
////////////////////////////////////////////////////////////////////////////  

// 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;
};
Now, if we rerun the previous snippet, the variable tmp will reference the same object as the variable bob, like so:
var bob = new Kitten();
var tmp = bob.setName('Bob');
tmp.setColor('black');
console.log(tmp === bob);  

// OUTPUT: //
> true
To shorten this even more, we do not even need to create the variable bob. Here are 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...


crazydeveloper Home Page 29 April 2015

Become a Fan