JavaScript/Notes/Singleton

From Noisebridge
< JavaScript(Difference between revisions)
Jump to: navigation, search
(Factory Method)
(Eager Initialization)
Line 17: Line 17:
 
</source>
 
</source>
  
== Eager Initialization ==  
+
== Eager Initialization ==
 +
 
 +
Not a Singleton, but a constructor.
 
<source lang="javascript">
 
<source lang="javascript">
 
// Not a Singleton.
 
// Not a Singleton.
Line 27: Line 29:
 
var anObject = new c();
 
var anObject = new c();
 
</source>
 
</source>
 +
Example: Constructors and prototype inheritance.
 +
[http://jsbin.com/IBAbIgI/6/edit jsbin]
  
 
Singleton:
 
Singleton:
Line 35: Line 39:
 
}(3);
 
}(3);
 
</source>
 
</source>
 +
[http://jsbin.com/ErAHEFo/1/edit jsbin]

Revision as of 00:21, 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, but a constructor.

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

Example: Constructors and prototype inheritance. jsbin

Singleton:

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

jsbin

Personal tools