javascript chaining method

by Shang-De You

JavaScript

// define the class
var Kitten = function() {
  this.name = 'Garfield';
  this.color = 'brown';
  this.gender = 'male';
  this.setName = function(name) {
    this.name = name;
    return this;
  };
  this.setColor = function(color) {
    this.color = color;
    return this;
  };
  this.setGender = function(gender) {
    this.gender = gender;
    return this;
  };
  this.save = function() {
    console.log(
      'saving ' + this.name + ', the ' +
      this.color + ' ' + this.gender + ' kitten...'
    );

    // save to database here...

    return this;
  };
};


var bob = new Kitten();

new Kitten()
  .setName('Bob')
  .setColor('black')
  .setGender('male')
  .save();