DEV Community

loading...

Exploring Factory Functions

vicradon profile image Osinachi Chukwujama Updated on ・1 min read

Looking at the words, factory and function would paint a picture of a function which creates objects. That's exactly what factory functions do. They are blueprints for object creation. More like classes. But milder, without the syntactic sugar.

Factory functions allow for speedy object creation by just calling the function with a few parameters here and there. Say we want a Sims factory. We would need a function which outputs Sims with the following properties:

  1. Name
  2. Age
  3. Gender

The factory

const makeSim = (name, age, gender) => {
  return {
    name, 
    age,
    gender
  };
}

The function simply returns an object.
Now that we have that in place, we can add methods to this object.

const makeSim = (name, age, gender) => {
  return {
    _name:name, 
    _age:age,
    _gender:gender,
    _occupation:occupation,
    _interests:interests, 
    get name() {return this._name},
    get age() {return this._age},
    get gender() {return this._gender}
  }
};
const Sam = makeSim('Samuel', 23, 'male');
console.log(Sam);    // outputs {name: "Sam", age: 23, gender: "male"}
console.log(Sam.name);    //outputs Samuel

So that's my little say on factory functions. Post your views on the topic in the comment section. Thanks.

Discussion

pic
Editor guide