Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Osinachi Chukwujama
Osinachi Chukwujama

Posted on • Edited on

     

Exploring Factory Functions

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:

  1. Name
  2. Age
  3. Gender

The factory

constmakeSim=(name,age,gender)=>{return{name,age,gender};}
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Learning server-side development. Creating courses on educative.io
  • Location
    Owerri Nigeria
  • Education
    Federal University of Technology Owerri
  • Joined

More fromOsinachi Chukwujama

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp