DEV Community

Discussion on: The Proper Way to Write Async Constructors in JavaScript

Collapse
 
reinoute profile image
Reinout

It's a creative solution for situations where you must use classes. I didn't know about this 'trick' and I would definitely use it if I have to!

But what I'm trying to explain is that classes in JS are just syntactic sugar. What you're essentially doing is modifying the default class functionality to make them behave more like functions. Then why not use normal functions in the first place?

Well, the point of using classes is to encapsulate some unit of state.

You can do exactly that with (normal) factory functions (example here). Including private/public variables and private/public methods. And the best thing, you don't have to worry about this anywhere.

It would be a good excercise to rewrite the Spotify example to use factory functions (not classes) and compare them.

Thread Thread
 
somedood profile image
Basti Ortiz

But what I'm trying to explain is that classes in JS are just syntactic sugar. What you're essentially doing is modifying the default class functionality to make them behave more like functions. Then why not use normal functions in the first place?

Oh, I see! I have slightly misunderstood. If that's the case, I must agree with your point. The static is essentially just a namespace based on my usage. To be fair, though, the namespace does make its relationship with the class explicit.

You can do exactly that with (normal) factory functions.

Indeed! In fact, I have written an article about that years ago as well. The idioms used in that article may be outdated by today's standards, but it's true that factory functions are sufficient for state encapsulation.

From a stylistic perspective, though, I personally prefer using classes for state encapsulation. The class fields make the state more apparent than if we were to use closures and factory functions. Also, classes were designed for this use case, anyway. 😂