JavaScript/Notes/Singleton

From Noisebridge
< JavaScript(Difference between revisions)
Jump to: navigation, search
(Eager Initialization)
(Factory Method)
Line 1: Line 1:
 
Singleton with information hiding.
 
Singleton with information hiding.
  
== Factory Method ==
+
== Lazy Initialization ==
 
<source lang="javascript">
 
<source lang="javascript">
 
function getAnObject(a) {
 
function getAnObject(a) {

Revision as of 00:09, 23 November 2013

Singleton with information hiding.

Lazy Initialization

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