4 ms·
A huge (from my perspective, at least) unsolved problem with the private members proposal is that you can't use it to build immutable objects, not realistically
by atombender 8y ago
A huge (from my perspective, at least) unsolved problem with the private members proposal is that you can't use it to build immutable objects, not realistically.
Without private members I can write something like:
class Fruit {
constructor(props = {}) {
Object.assign(this, props)
Object.freeze(this)
}
withSize(size) {
return new Fruit({...this, size})
}
}
Now I can do:
fruit = new Fruit({kind: 'apple'})
// Later:
saveFruitToDatabase(fruit.withSize(20))
This pattern works great, overall, though it isn't performant. With private members, you'd think you could declare them and also update objects using transformations. But private members don't work with Object.assign(), .entries() etc., and aren't introspectively at all. So you can't write withSize() to do partial updates without spelling out all the field names, every time.
Turns out it's quite hard to write robust, performant immutable code in JS. (Yes, I know immutable.js has Record. However, it's not compatible with getters and setters.)