From fa71554b169a9b6f7fa6ba72c7173e899890d94d Mon Sep 17 00:00:00 2001 From: Jonathan Persson Date: Sun, 2 Aug 2015 11:08:43 +0200 Subject: [PATCH] Simplify the singleton code example by comparing object references instead of random numbers. --- book/index.html | 23 +++-------------------- 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/book/index.html b/book/index.html index 949fe076..b414c218 100644 --- a/book/index.html +++ b/book/index.html @@ -1512,8 +1512,6 @@

var privateVariable = "Im also private"; - var privateRandomNumber = Math.random(); - return { // Public methods and variables @@ -1521,11 +1519,7 @@

console.log( "The public can see me!" ); }, - publicProperty: "I am also public", - - getRandomNumber: function() { - return privateRandomNumber; - } + publicProperty: "I am also public" }; @@ -1557,14 +1551,8 @@

// Singleton - var privateRandomNumber = Math.random(); - return { - getRandomNumber: function() { - return privateRandomNumber; - } - }; }; @@ -1588,16 +1576,11 @@

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

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