3 ms·
The way how Addy Osmani implements singleton pattern is rather disputable. I would implement singleton as a regular object that returns itself immediately if in
by jarek-foksa 14y ago
The way how Addy Osmani implements singleton pattern is rather disputable. I would implement singleton as a regular object that returns itself immediately if initialized for the second time.
His prototype pattern also doesn't look like the right way of doing things. Is there actually anyone that uses plain object descriptors? I would just create helper method that wraps Object.create() and takes prototype object as first argument and instance object as second argument. There is no need to use constructors in this pattern (either directly or inside helpers) unless you are targetting legacy browsers.
I also dislike the fact that public/local scope is emulated by misusing the return statement - this is ugly, confusing and it doesn't play nicely with other patterns such as prototype. If you need some notion of public/private scope then just use underscore notation.
- Androsynth 14y agoThe singleton pattern he presents is pretty common and pretty powerful. It is a self-invoking module. It allows you to use the module pattern (very solid js pattern) and probably has less code than your method. Also, javascript has closures, use them. this._private is a hacky java-esque way of doing things. return {public_methods...} is a solid way of working towards the strengths of the language and doing proper js encapsulation. As for the prototype pattern, there are a million ways you can do that. Best to learn the fundamentals so you can use whatever works best based on the situation. edit: I should add that one of the reasons I like JS patterns is that there are multiple correct ways to implement them based on the situation. There are many wrong ways too, of course :) but it is a very flexible language.
- jarek-foksa 14y agoHere 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?