by gorgoiler · 6y ago · 0 comments
If one can compose ones problem into a lot of classes of object that only have one method then it is quite acceptable to just use closures instead:
HI = ‘Hello’
def greeter(title, name):
def f():
print(HI, title, name)
return f
I wrote a whole bunch of Python like this, yesterday. It felt liberating! So terse!Downside: one very common reason to have more than one method in a class is to define __str__. There will be no pretty debug printable version of my greeter() “class” for me, alas.
That also works in JavaScript:
function Fraction(a, b) {
this.value = function () {
return a / b;
}
}
const half = new Fraction(1, 2);
It feels weird to me, that classes were eventually introduced in JS.if you don't put value in the Fraction prototype, then value will be created each time Fraction is instanced.
But that's not why class where created. Class simplify writing classes, doing inheritance and introduce "super" static binding which wasn't possible before with functions.
Also, JS will now force you to use new when instanciating Fraction class as an object. You can't call it like a function.