4 ms·
It's a cool idea, and I'm sure everyone gets a pleasant jolt when they make the connection (I sure did), but you probably already understood this idea at some s
by munchbunny 6y ago
It's a cool idea, and I'm sure everyone gets a pleasant jolt when they make the connection (I sure did), but you probably already understood this idea at some subconscious or conscious level in order to get anything nontrivial done with a functional language.
It's one of the first things you're taught if you are learning a functional-at-its-roots language. Not JavaScript, which is mixed-paradigm at its roots. For me it was Scheme in college.
If you're learning a functional language, combining closures and functions that return functions to carry around "instance fields" and "instance methods" is what you learn right after you've gotten over the basics like map/filter and tail recursion. The equivalence of this pattern to classes is something you'll understand intuitively, even if you haven't put words to it yet.
- commandlinefan 6y ago> Not JavaScript Funny enough, I actually had the referenced epiphany while learning JavaScript, since this idiom is so common in it.
- munchbunny 6y agoIs it actually that common? Using a higher order function that returns member fields/methods which you then actually call? Higher order functions are common in JavaScript, and closures are as well, but I don't recall seeing them used as substitutes for classes or vice versa for years at this point. With JavaScript you don't have to use closures and higher order functions to do modularization because you have classes, and you don't have to use the functor pattern (like Java before Java 8) because you have higher order functions. ES5's syntax for object types looked a lot more like "closures with syntax sugar" than ES6 and later JavaScript syntax with explicit class declarations.
- d13 6y agoE6 “classes” are just functions that return objects.
- Weebs 6y agoIt's probably not common, but for me the answer lies here: > I don't recall seeing them used as substitutes for classes or vice versa for years at this point I had a fairly large school project developing a JavaScript application back before ES6, and kept searching for a better way to structure my code because I found it awkward using prototypes + binding this for events. Eventually I found a hidden golden nugget of a tutorial that showed me how to do it with closures and I was in awe that it somehow wasn't the norm (and obviously how cool it was to build objects out of functions!)