Jump to Categories

Factory pattern

var animal = function(type, noise) {
  var atr = {};
  atr.type = type;
  atr.makeNoise = function() {
    return noise;
  }
  return atr;
}

var penny = animal('pig', 'Oinkkk');
// Pig
console.log(pig.type);

var darren = animal('dog', 'Wooofff');
// Wooofff
console.log(dog.makeNoise());


// ES6
const animal = (type, noise) => {
  const atr = {};
  atr.type = type;
  atr.makeNoise = () => {
	return noise;
  }
  return atr;
};

Codepen example

Refs