3 ms·
I mean that with the minimalist approach you can define static methods in your 'class' body, thus grouping them neatly together: MyClass = { getInstance: f
by gabordemooij 15y ago
I mean that with the minimalist approach you can define static methods in your 'class' body, thus grouping them neatly together:
MyClass = {
getInstance: function(){ ... }
}
vs
MyClass = function(){
}
//outside function body...
MyClass.prototype.getInstance = function(){ ... }
- stephenr 15y agoMyClass = function(){ } //outside function body... MyClass.prototype.getInstance = function(){ ... } but this makes no sense - why would you have a "static" method defined as an instance method? in this example you would do: var MyClass = function (){}; // constructor MyClass.getInstance = function (){}; // static method MyClass.prototype.start = function (){}; // instance method
- gabordemooij 15y agoI think the nested notation is simply more maintainable. MyClass = { staticMethod: function(){ } createNew: function() { obj = {}; obj.instanceMethod = function(){} return obj; } } Also, I find it quite elegant to see that the constructor function (factory method) is implemented as a static method as well). Of course I know these aren't static methods like in Java/PHP but in practice they can treated as such.
- stephenr 15y ago> I think the nested notation is simply more maintainable why though? I don't see how being part of an object literal is inherently more maintainable? > Also, I find it quite elegant to see that the constructor function (factory method) is implemented as a static method as well) but you were harping on about "OOP standards" and "best practices" before - since when is the constructor for a class a static method? In a language with true classes, even with a Singleton, the constructor is an instance method.
- gabordemooij 15y agoUhm, no... http://php.net/manual/en/language.oop5.patterns.php http://php.net/manual/en/language.oop5.patterns.php A singleton uses a static factory method in PHP and Java. AFAIK there is no (mainstream) language where a singleton is an instance method.
- stephenr 15y agoNo, a singleton still has a constructor though - it's just not public. It's called when the factory method creates a new instance. the factory static method is NOT the constructor.
- gabordemooij 15y agoYes this is correct. The constructor in a singleton pattern is private. I meant the way to obtain an instance is the same. Sorry for my mistake.