My Singleton experiments
Experiments in creating an extensible Singleton. Follows the DRY rule.
by b_long
HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
JavaScript
Ext.ns("b_long.polyfil");
b_long.polyfil.AbstractSingleton = {};
b_long.polyfil.AbstractSingleton.getInstance = function () {
if (b_long.polyfil.AbstractSingleton._singletonInstance) {
return b_long.polyfil.AbstractSingleton._singletonInstance;
} else {
b_long.polyfil.AbstractSingleton._singletonInstance = this;
return b_long.polyfil.AbstractSingleton._singletonInstance;
}
};
b_long.polyfil.Singleton1 = $.extend(b_long.polyfil.AbstractSingleton, {
x: "Singleton1 x val",
say: function(){
console.log(this.x)
}
});
var anotherInst = b_long.polyfil.AbstractSingleton.getInstance();
anotherInst.say(); //alerts 10
(function () {
var privateVar = "I'm a subclass...";
function privateFn (){
console.log("Calling superclass' say()");
x = privateVar;
say(x);
console.log("Called superclass' say()!");
}
var publicApi = {
sweet: function () {
console.log("sweet");
},
publicFn: privateFn
};
b_long.polyfil.NewSingleton = $.extend(b_long.polyfil.AbstractSingleton, publicApi);
}());
var newSingletonInstance = b_long.polyfil.NewSingleton.getInstance();
newSingletonInstance.x = "Set at the subclass"
newSingletonInstance.say();
newSingletonInstance.publicFn();
// anotherInst should have the same type (an be the same instance) of b_long.polyfil.AbstractSingleton.getInstance()
console.log(anotherInst === b_long.polyfil.AbstractSingleton.getInstance() ? "very cool" : "not cool");
// newSingletonInstance should NOT have the same type (an be the same instance) of b_long.polyfil.AbstractSingleton.getInstance()
console.log(typeof newSingletonInstance); // "object"
// Uncaught TypeError: Expecting a function in instanceof check, but got [object global]
//console.log(newSingletonInstance instanceof b_long.polyfil.AbstractSingleton);
//console.log(newSingletonInstance instanceof b_long.polyfil.NewSingleton);...