Hello, World! π
I've been learning JavaScript for a while now, and recently I've been spending more time with objects, constructors, classes, and factory functions.
At first, I thought I just needed to understand what each one does.
Now I understand them a little better...
And somehow, that has created another problem. π
When am I actually supposed to use each one?
From what I've learned so far:
Objects can hold data and behavior.
Constructors can be used to create multiple objects with similar properties and methods.
Classes provide another way of creating objects and are useful for things like inheritance.
Factory functions can create and return objects without using new.
Okay, I understand that.
But when I'm actually building something, how do I decide?
For example, let's say I need to create multiple objects with similar properties and methods.
I could use a class.
I could use a constructor function.
I could use a factory function.
So... which one do I pick? π
And then another question came to my mind.
Can I use more than one?
Suppose I'm working on a bigger project.
Could I have something like:
A class for one type of object
A factory function for another
Plain objects for some application data
Or should I generally try to stick to one approach?
I don't know if mixing them is perfectly normal or if I'm just creating unnecessary complexity.
So I'm asking experienced developers:
How do you decide?
Do you have a rule of thumb for choosing between classes, constructors, and factory functions?
And if you've used more than one approach in the same project, what made you choose each one?
I'm not looking for someone to tell me βjust use X.β
I'm trying to understand the reasoning behind the choice.
Right now, I'm learning the syntax.
I want to start learning how developers actually make these decisions when building real projects.
Would love to hear your thoughts.
Thanks! π
Top comments (1)
Plain objects for data, most of the time. If it only holds values and gets passed around, saved or sent to an API, it does not need to be anything else.
I reach for a class when the thing has state that changes and methods that change it. Factory functions when I want something private that callers cannot touch. Vue composables are basically that, and it is where I write most of mine.
Mixing them in one project is normal. What gets confusing is two different ways of making the same kind of thing. Pick one per kind and stay with it.