JavaScript/Notes/Singleton

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

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 c = function(a) {
  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