3 ms·
Another perspective on static blocks is what they replace/help migrate away from. Static blocks are one of the last pieces of the puzzle holding some projects (
by WorldMaker 5y ago
Another perspective on static blocks is what they replace/help migrate away from. Static blocks are one of the last pieces of the puzzle holding some projects (or at least some particularly old legacy objects in those projects) from migrating to the new class syntax. For better or worse the classic Constructor Function pattern of building objects in JS was full of static initialization code (as it was an easy thing to do in that pattern). Static blocks bring back a way to do that in class syntax while adopting the better scoping rules of class syntax, helping more projects move away from Constructor Functions to class syntax.
- qsort 5y agoYeah, this makes a lot of sense. ES6 classes are restrictive if you look at them from a pre-ES6 perspective. Of course many of those restrictions are "right", but they are restrictions nonetheless. I guess it's a good way to bring back that behavior with the added bonus of being useful by itself in some limited but legitimate cases (sibiling comment mentioned cache initialization, also a good point).
- galaxyLogic 5y agoHere's a pattern I've been using for some time in ES6 JavaScript (on Node.js) : module.exports = class MyClass { // ... static init () { // ... do something, like create and // cache a Singleton etc. return this; } } . init(); The static method init() is executed only once when the class is created and exported. You could add some check to it that causes an error if it gets called more than once. Do static blocks allow me to do something more?