Everywhere I saw an implementation of singleton in javascript in a such manner:
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
Here we can see that it returns a function which we must call in order to get an object. Question: Why we can't just write like this:
var Singleton = (function () {
function privateMethod() {
...
}
return {
publicMethod1: function() { },
publicMethod2: function() { },
};
})();
Somebody will say that reason is for inheritance support. However, I don't see a difference. Anyway Singleton is an object now.
Aucun commentaire:
Enregistrer un commentaire