Intro: I start to read Javascript Patterns book and can't grasp one example. It's pretty big so I'll try to explain it briefly before getting you a code.
Examples explanation: So what they try to do is to define singleton with help of Closure. The first piece of code is pretty simple, but it has one significant drawback - we can't redefine prototype after creating the first instance of Universe.
Question: Could someone explain me how does the second example ('Good' singleton) code manage to change prototype after first constructor call?
'Bad' singleton:
function Universe() {
var instance = this;
this.start_time = 0;
this.bang = "Big";
Universe = function () {
return instance;
};
}
// testing
Universe.prototype.nothing = true;
var uni = new Universe();
Universe.prototype.everything = true;
var uni2 = new Universe();
uni.nothing; // true
uni2.nothing; // true
//AS YOU CAN SEE ALL CHANGES TO UNIVERSE PROTOTYPE HAVE NO RESULT AFTER FIRST CONSTRUCTOR CALL
uni.everything; // undefined
uni2.everything; // undefined
And then they solve the problem with code below:
'Good' singleton:
function Universe() {
var instance;
Universe = function Universe() {
return instance;
};
Universe.prototype = this;
instance = new Universe();
instance.constructor = Universe;
instance.start_time = 0;
instance.bang = "Big";
return instance;
}
// testing
Universe.prototype.nothing = true;
var uni = new Universe();
//QUESTION: how does it manage to change the prototype of singleton?!
Universe.prototype.everything = true;
var uni2 = new Universe();
uni.nothing && uni.everything && uni2.nothing && uni2.everything; // true
The same question in other words: why in the first code snippet uni.everything == false and uni2.everything == false but in the second one uni.everything == true and uni2.everything == true? As for me, they should be false in both cases