JavaScript/Notes/Singleton

From Noisebridge
< JavaScript(Difference between revisions)
Jump to: navigation, search
(Factory Method)
(Eager Initialization)
Line 18: Line 18:
  
 
== Eager Initialization ==  
 
== Eager Initialization ==  
 +
<source lang="javascript">
 +
// Not a Singleton.
 +
var a = function(c) {
 +
  var b = a + 2;
 +
  this.name = b;
 +
};
 +
 +
var anObject = new c();
 +
</source>
 +
 
<source lang="javascript">
 
<source lang="javascript">
 
var anObject = new function(a) {
 
var anObject = new function(a) {

Revision as of 21:05, 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 a = function(c) {
  var b = a + 2;
  this.name = b;
};
 
var anObject = new c();
var anObject = new function(a) {
  var b = a + 2;
  this.name = b;
};
Personal tools