Menu

Post image 1
Post image 2
Post image 3
1 / 3
0

Factory Functions vs Classes: If Classes Exist, Why Do We Still Use Factory Functions?

DEV Community·Ashay Tiwari·3 months ago
#AdhCIsDr
#dev#fullscreen#factory#objects#name#article
Reading 0:00
15s threshold

❓ A Question That Confused Me As we continue learning Object-Oriented Programming, I want to pause for a moment and discuss something that often comes up for JavaScript developers. When we hear about OOP, we usually hear about classes. class User { constructor ( name ) { this . name = name ; } } Enter fullscreen mode Exit fullscreen mode We've discussed that classes are used to create objects. Fair enough. But then we look at JavaScript codebases and see something like this: function createUser ( name ) { return { name }; } Enter fullscreen mode Exit fullscreen mode No class. No constructor. No new keyword. And yet, we're still creating objects. This raises a very reasonable question: What is this called? And if these kinds of functions can create objects, why do classes exist? To answer that, let's first understand the problem developers were trying to solve. The Simplest Possible Approach Suppose we're building an application and need user objects.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More