4 ms·
Without the "getter syntactic sugar": let lea = { name:"Lea verou", getId:function() { return this.name.toLowerCase().replace(/\W+/g, "-");}
by astrobe_ 6y ago
Without the "getter syntactic sugar":
let lea = {
name:"Lea verou",
getId:function() { return this.name.toLowerCase().replace(/\W+/g, "-");}
};
lea.getId() // lea-verou
lea.getId=function() { return this.name; }
lea.getId() // Lea Verou
"syntactic sugar causes cancer of the semicolon" -- A. Perlis
That said, I don't use JS and I agree it still looks like a bad idea, although this is not too heretic in a prototype-based-like language.
- eyelidlessness 6y agoI’m on mobile so forgive any syntax mistakes, but I’m talking more along the lines: const createLea = (data) => ({ ...data, id: ( data.id ?? data.name .toLowerCase() .replace(/\W+/g, '-') ), }); No mutation, no getters (function or implicit), dead simple to use, dead simple to reassign (just call the function again with the same data but provide a new `id` and super easy to understand at a glance (easier with types, but I digress). > prototype-based-like language One of the benefits of the approach I describe is you’re no longer working in a prototype based language. I mean, of course you are, but you don’t have to care. Edit: even on mobile I couldn’t stand the formatting. Edit 2: since I mentioned performance in my original comment, I’d add that there are two benefits here (one real, one possible with JITs): getters and setters (and anything with Object.defineProperty) perform worse than regular values; if you program in this style, the JIT has an opportunity to recognize that your values are generally immutable and optimize object construction e.g. with the spread operator as persistent data structures the same way FP languages do.