Jump to Categories

Factory pattern

A factory function is any function which is not a class or constructor that returns a (presumably new) object. In JavaScript, any function can return an object. When it does so without the new keyword, it’s a factory function. Eric Elliott
const animal = (type, noise) => {
  const atr = {};
  atr.type = type;
  atr.makeNoise = () => {
    return noise;
  }
  return atr;
};

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

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

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

Providing an object to the factory

const factory = ({name, age}) => ({
  name,
  age,
  sayPerson () {
    return `Hello ${name}, you are ${age}`;
  }
});

const shane = factory({name: 'Shane', age: 31});

// {name: "Shane", age: 31, sayPerson: ƒ}
console.log(shane);

Codepen example

Refs