"A factory function is a function which returns an object". Yes, it's a function that returns an object. It's that simple. Let's dive in...
Below is the code snippet
const sudi = {
name: 'Sudi',
details(){
console.log(`Hello, I am ${this.name}`)
}
}
sudi.details() //Hello, I am Sudi
const rohit = {
name: 'Rohit',
details(){
console.log(`Hello, I am ${this.name}`)
}
}
rohit.details() //Hello, I am Rohit
So we have two objects which have the same attributes and return somewhat similar results. If we have to create more instances that describe some more students, we need to create more objects. Its a repetitive task and code duplication.
Here comes the factory function to the rescue.
Ok. Let's focus now...
function getStudentDetails(name){
return {
getStudentName(){
console.log(`Hello I am ${name}`)
}
}
}
const sudi = getStudentDetails('Sudi')
sudi.getStudentName() //Hello I am Sudi
const rohit = getStudentDetails('Rohit')
rohit.getStudentName() //Hello I am Rohit
So now we have a function that returns an object and when we create a student instance like sudi , we can call getStudentName() to get our desired result. That is it. We can create multiple instances of students and there is no code duplication.
Pros of using Factory Functions are
No code duplication
Its simple. You just return the object. In case of classes, you will need to have a constructor, use the super() keyword at times.
Data Privacy. We can create private variables which cannot be accessed from outside. We will talk about this in another article.
Cons
One of the cons that I see with factory function is that each function gets attached to its own object rather than in the prototype. So if we make any modification in
sudi.getStudentName()
, it will not reflect inrohit.getStudentName()
. This is not same in the case of Constructor functions.So this means it requires more memory since every function is latched onto its object and also in the case of multiple objects, if we need to change the implementation in
getStudentName()
function, we have to do that for every object. We will talk about this more in a different article.
Conclusion
I hope I was able to give a brief introduction to factory function. So a factory function is a function that returns an object. You can create object without using new keyword, keeps your code clean and avoids duplicate code while creating multiple objects.
Feel free to comment if I have missed something.