Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 3 additions & 20 deletions book/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1512,20 +1512,14 @@ <h2 id="singletonpatternjavascript">

var privateVariable = "Im also private";

var privateRandomNumber = Math.random();

return {

// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},

publicProperty: "I am also public",

getRandomNumber: function() {
return privateRandomNumber;
}
publicProperty: "I am also public"

};

Expand Down Expand Up @@ -1557,14 +1551,8 @@ <h2 id="singletonpatternjavascript">

// Singleton

var privateRandomNumber = Math.random();

return {

getRandomNumber: function() {
return privateRandomNumber;
}

};

};
Expand All @@ -1588,16 +1576,11 @@ <h2 id="singletonpatternjavascript">

var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // true
console.log( singleA === singleB ); // true

var badSingleA = myBadSingleton.getInstance();
var badSingleB = myBadSingleton.getInstance();
console.log( badSingleA.getRandomNumber() !== badSingleB.getRandomNumber() ); // true

// Note: as we are working with random numbers, there is a
// mathematical possibility both numbers will be the same,
// however unlikely. The above example should otherwise still
// be valid.
console.log( badSingleA !== badSingleB ); // true
</pre>

<p>What makes the Singleton is the global access to the instance (generally through <code>MySingleton.getInstance()</code>) as we don't (at least in static languages) call <code>new MySingleton()</code> directly. This is however possible in JavaScript.</p>
Expand Down