JavaScript/Notes/Singleton

From Noisebridge
< JavaScript(Difference between revisions)
Jump to: navigation, search
(Eager Initialization)
(Factory Method)
Line 5: Line 5:
 
function getAnObject(a) {
 
function getAnObject(a) {
 
   var anObject;
 
   var anObject;
 +
 +
  var b = a + 1;
  
 
   return (getAnObject = function() {
 
   return (getAnObject = function() {
 
     if(! anObject ) {
 
     if(! anObject ) {
       anObject = {name: a};
+
       anObject = {name: b};
 
     }
 
     }
 
     return anObject;
 
     return anObject;

Revision as of 11:55, 20 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

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