Reading the definition of the singleton function I can see how it is a singleton.
But the usage is what confuses me, don’t you have to call getInstance?
var mySingleton = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public"
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
// Usage:
var singleA = mySingleton;
var singleB = mySingleton;
console.log( singleA === singleB ); // true
Jerry has what is probably supposed to be in your example as the last three lines, but I think you need more of an understanding of what is going on in this code to understand why both the example Jarry provided and your original code evaluate to true.
Take for instance this line of code in your original example:
What you’re saying here is that singleA equals the reference to mySingleton, then when you assign mySingleton to singleB, you are just giving singleB the same exact reference to mySingleton (no code is called within mySingleton, you are just setting a reference). So you are comparing the same exact reference to itself: the reference to mySingleton.
Here’s how Jarry’s code works, take the line:
This causes the mySingleton object to actually call a function within it that creates a singleton object. On the first call of this function it creates a new object in the code, and on every subsequent call it will return that same object that was created (this is based on the code within init()).
This means that when you use mySingleton.getInstance you are creating a new object and setting singleA as a reference to that object. Then when you call “mySingleton.getInstance()” for “var singleB = mySingleton.getInstance()” it is returning the reference for the same object that was created on the previous line and assigning it to singleB. So when you are all said and done, the comparison singleA === singleB is true because you are comparing the same exact reference to itself: a reference to the object created by mySingleton.