Looking at the words,factory andfunction 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:
- Name
- Age
- Gender
The factory
constmakeSim=(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.
constmakeSim=(name,age,gender)=>{return{_name:name,_age:age,_gender:gender,_occupation:occupation,_interests:interests,getname(){returnthis._name},getage(){returnthis._age},getgender(){returnthis._gender}}};constSam=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.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse