Hacker News new | ask | show | jobs
by aboodman 619 days ago
Hello JS was my first language and I use classes because sometimes it seems like the obvious way to model things.

Looking through the source of Replicache, here are some classes we use:

- KVStore

- DAGStore

- Transaction

I mean ... I can of course model these w/o classes, but encapsulating the state and methods together feels right to me. Especially when there is private state that only the methods should manipulate.

We use composition all over the place and rarely use inheritance so I don't think it's just some deficiency of knowledge .

Pre JS classes, the js community emulated classes w/ the prototype chain and that's what I'd have done for these classes if real JS classes weren't available.

2 comments

closures can encapsulate state and methods classes are syntactic sugar

emulating classes is, imo, exactly the problem

using factory functions which create and return an object, with variables passed to and created in the function, handles encapsulation

and there is no `this` to deal with

Honestly, all this “emulated with prototypes” meme is misleading. Prototypes are an implementation of what they’ve called “binding” before (some may recognize “early” and “late” in this context). That’s how classes work and what classes are. The fact that some gears got exposed to a user [to stick their fingers into] doesn’t change much.

So no, javascript didn’t really “add classes”. It just had a very annoying lower-level syntax for them from the beginning and fixed it after a while. It wouldn’t survive the pressure if it had no classes at all cause this idea is fundamental to programming and to how we think: you-do.

One may pretend to not have classes through closures, but technically that’s just classes again, cause you have a bunch of functions with a shared upvalue block. You just hold it the other way round lexically, by a method instead of a context.

I believe this common idea of alienating classes stems from the general OOP stigma since the times of “design patterns”.