JavaScript/Notes/Singleton

From Noisebridge
< JavaScript(Difference between revisions)
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 21:07, 22 November 2013

Singleton with information hiding.

Factory Method

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

Eager Initialization

// Not a Singleton.
var c = function(a) {
  var b = a + 2;
  this.name = b;
};
 
var anObject = new c();

Singleton:

var anObject = new function(a) {
  var b = a + 2;
  this.name = b;
}(3);
Personal tools