3 ms·
Here is what I prefer to call a singleton in JS, I don't think it could be any simpler than that: mySingleton = { initialized: false, init: function
by jarek-foksa 14y ago
Here is what I prefer to call a singleton in JS, I don't think it could be any simpler than that:
mySingleton = {
initialized: false,
init: function() {
if (this.initialized == false) {
this.initialized = true;
// Initialize the singleton here
}
return this
},
}
singleton1 = mySingleton.init()
singleton2 = mySingleton.init()
Both underscore notation and returning "public" methods feel awkward in JavaScript, though the
second appraoch introduces major trade-offs which I belive are not worth it. E.g. how do you create inheritance chains
when using this pattern? Are you just copying public methods returned from one object into another? Or how do you inspect private properties in Dev Tools? Are you setting breakpoints for that purpose?