Fluent Interface in JavaScript

Fluent Interface in JavaScript

Welcome back. If you haven't read the first article about this topic kindly start from this before you continue

In the first article, we have examined what is Fluent Interface in PHP. In this one we shall be looking into some JavaScript implementation of that. Lets dive in straight away with the following code.

var Person = function() {
  this.name = '';
  this.sex = '';
  this.age = '';
  this.height = '';
  this.weight = '';
};

Person.prototype.name = function(name) {
  this.name = name;
  return this;
};

Person.prototype.sex = function(sex) {
  this.sex = sex;
  return this;
};

Person.prototype.age = function(age) {
  this.age = age;
  return this;
};

Person.prototype.height = function(height) {
  this.height = height;
  return this;
};

Person.prototype.weight = function(weight) {
  this.weight = weight;
  return this;
};


Person.prototype.save = function() { 
  let str = '';
  for(let property of Object.keys(this)){
    str += this[property] + ' ';
  } 
  console.log(str);
};

Using it

let person = new Person();
person.name('John').sex('Male').age('20').height('5.8').weight('78').save();

// Outputs
 John Male 20 5.8 78

Hope this helps? Happy Coding. Follow me on twitter

mobile.twitter.com/Ifeanyi_chukwuJ