3 ms·
> but I never quite understood what is so poor about a tuple of functions closed over same data into a closure. Apart from inheritance, what does it lose. In t
by Izkata 6y ago
> but I never quite understood what is so poor about a tuple of functions closed over same data into a closure. Apart from inheritance, what does it lose.
In the closure-based version, getFullName and setFirstName are defined anew for each instance of Person, using more memory each time. Typically isn't an issue unless you're creating a massive number of them, but the class-based version doesn't have this problem.
Also, just to throw it in the mix as well, the class-based version I believe is largely just syntactic sugar over the traditional way of creating objects in javascript, using prototype-based methods:
function Person(firstName, lastName) {
this.fName = firstName;
this.lName = lastName;
return this;
}
Person.prototype.getFullName = function() {
return this.fName + ' ' + this.lName;
}
Person.prototype.setFirstName = function(firstName) {
this.fName = firstName
}
const person = new Person("Ben", "Bitdiddle")
person.getFullName()
Prototypical inheritance is interesting in that an instance of Person could be used as the class for another object, ad infinitum.
- wruza 6y agoAn optimizing compiler could easily detect that a bunch of closures share an upvalue block in an enclosing "constructor" and then instead make that block explicit, and rewrite an entire constructor in a way that doesn't involve multiple closures at all (given that escape analysis and lang rules allow that). E.g.: // optimized function constructor(...) { let this = {...} function method(this, ...) {...} return function (name, ...) { switch (name) { case 'method': return method(this, ...) // or return a temp closure // like it does in tfa constructor()('method', 42) And vice versa, on a computer that does closures in hardware better than objects for some unrealistic reason. That's why both are just abstractions, whose semantics may better fit one or another implementation, but it really doesn't matter for maths.