JS Creational Pattern

by bhupendra negi

HTML

<h2>
 JS Design pattern
</h2>
<ul>
<li>Creational
<ul>
<li> Constructor </li>
<li> Prototype </li>
<li> Factory </li>
<li> Module </li>
</ul>
</li>
</ul>

JavaScript

// creational
function Person(fName,lName)
{
 this.fName = fName;
 this.lName = lName;
 this.displayName = function() {
 return this.fName+'---'+lName;
 }
}

var p1 = new Person("Ram","Mohan");
console.log(p1.displayName());
console.dir(p1);
var p2 = new Person("Shyam","Mohan");
console.log(p2.displayName());
console.dir(p2);
// drawback : displayName fn is getting created for each Person Object
/***************Prototype********************************************/
/*Person.prototype.showFullName = function() { return this.fName+'***'+this.lName};
*/

Person.prototype = { showFullName1 : function () { return this.fName+'***'+this.lName},
showAlert : function() { alert("hi!");}
};

var p1 = new Person("RamP","Mohan");
//p1.showAlert();
console.log(p1.showFullName1());
console.dir(p1);
var p2 = new Person("ShyamP","Mohan");
console.log(p2.showFullName1());
console.dir(p2);

/*********** Factory pattern **************************/
//Creates objects on specific requirements / configurations 

function carFactory(){
this.createCars = function(type) 
  {
  var obj;
  switch(type) {
  case "suv" : obj = new SUV();break;
  case "hatch": obj = new Hatch();break;
  default: obj = new Sedan();break;
  }
  obj.type = type;
  obj.getCarInfo = function(){
  console.log(this.type + " type of car has mileage of "+ this.mileage + "km/h");
  } 
  return obj;
}
}


 function SUV() {
 this.mileage = 12;
 }
 
 function Hatch() {
 this.mileage = 24;
 }
 function Sedan() {
 this.mileage = 18;
 }
 
 var car = new carFactory();
 console.log(car);
 var c1 = car.createCars("suv");
 console.log(c1.getCarInfo());
 var c2 = car.createCars("hatch");
 console.log(c2.getCarInfo());
 
 //******** Module pattern **********************//
 // encapsulates a group of methods for common purpose
 //, only interface exposed , implementation is private
 // its lke exposing public api, use as a service
 
var EventService = function  () {

return {

register : function(name){
console.log("Register for...