Permalink
Browse files

Updated singleton pattern example

  • Loading branch information...
1 parent 37e41ae commit 7e6d70bdbaa67836d2797a41fec1130ecfcdb20b @wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww committed Jan 22, 2013
Showing with 9 additions and 2 deletions.
  1. +9 −2 book/index.html
View
11 book/index.html
@@ -1478,14 +1478,21 @@ <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"
+ publicProperty: "I am also public",
+
+ getRandomNumber: function() {
+ return privateRandomNumber;
+ }
+
};
};
@@ -1511,7 +1518,7 @@ <h2 id="singletonpatternjavascript">
var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
-console.log( singleA === singleB ); // true
+console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // 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>

0 comments on commit 7e6d70b

Please sign in to comment.