Difference between revisions of "JavaScript/Notes/Singleton"

From Noisebridge
Jump to: navigation, search
(Eager Initialization)
(Eager Initialization)
Line 28: Line 28:
 
</source>
 
</source>
  
 +
Singleton:
 
<source lang="javascript">
 
<source lang="javascript">
 
var anObject = new function(a) {
 
var anObject = new function(a) {
 
   var b = a + 2;
 
   var b = a + 2;
 
   this.name = b;
 
   this.name = b;
};
+
}(3);
 
</source>
 
</source>

Revision as of 04:07, 23 November 2013

Singleton with information hiding.

Factory Method

<source lang="javascript"> function getAnObject(a) {

 var anObject;
 var b = a + 1;
 return (getAnObject = function() {
   if(! anObject ) {
     anObject = {name: b};
   }
   return anObject;
 })();

} </source>

Eager Initialization

<source lang="javascript"> // Not a Singleton. var c = function(a) {

 var b = a + 2;
 this.name = b;

};

var anObject = new c(); </source>

Singleton: <source lang="javascript"> var anObject = new function(a) {

 var b = a + 2;
 this.name = b;

}(3); </source>