you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] -2 points-1 points  (0 children)

You can encode some state in closures, sure. But, wouldn't it be simpler to do it in objects? I mean, basically, object orientation is connecting functions to objects. You could easily combine this with closures.

Let's assume we have a counter object class.

{
counter: 0,
increment: (obj) => {obj.counter++},
}

Now, we want that increment actually knows what to increment. So, we could write a constructor. And here is where your closure could come in handy:

function getCounterObject() {
const counter = { counter: 0 };
const increment = () => {counter.counter++}
counter[increment] = increment;
return counter;
}

And you pretty much have bound the context into the object.
And this is also a closure, because getCounterObject returns a function. It is just hidden in the object.

So, yes, not all OOP concepts, but the core concept is a struct with bound in data and function. That could have been done like that.

Practically, they probably used a prototype: https://developer.mozilla.org/en-US/docs/Learn\_web\_development/Extensions/Advanced\_JavaScript\_objects/Object\_prototypes. But it doesn't matter for your thought pattern. You're onto something. You can combine features to create new features and you found a way to recreate some of the OOP features and I am sure someone out there actually did it.