Design paterns in js

by rishul matta

JavaScript

// Inheritance :

function Beverage (name , temperature) {
	this.name = name;
  this.temperature = temperature;
}

Beverage.prototype.drink = function () {
	console.log(" I'm drinking " + this.name )
}



function Coffee (type) {
	Beverage.call(this,"coffee","hot");
  //calling parent constructor
	this.type = type;
}


Coffee.prototype = Object.create(Beverage.prototype); //implementing prototypal inheritance

//the reason we write above is so that we can do the following :

var cof = new Coffee("dark");
cof.drink(); //it calls beverage method


//--------------------------------------

//2. Mixins -- have the prototype properties on an object and use jquery extend method to add it to prototype this way you dont have to define the same methods on diff prototype of diff classes agin and again

//-----------------------------------------

//3.singleton is an extension of module pattern :

var obj = (function() {
	var instance;
  var counter = 0;
  
  function createInstance () {
  	return {counter : counter}
  }
  
  function getInstance () {
  	 return instance || (instance = createInstance())
  }
  
  return getInstance;
 
})()

var a = obj()

var b = obj ()

console.log (a === b) //true as both refering to the same object