JavaScript/Notes/Singleton

From Noisebridge Wiki
Revision as of 04:45, 10 February 2026 by Maintenance script (talk | contribs) (Imported from Noisebridge wiki backup)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Singleton with information hiding.

Constructors[edit]

Before going over Singleton patterns, lets first take a look at how constructors work.

Lazy Initialization[edit]

This example of a Singleton uses my patented "function rewriting" technique, where `getAnObject` is identifier is reassigned to the nested closure.

function getAnObject(a) {
  var anObject;

  var b = a + 1;

  return (getAnObject = function() {
    if(! anObject ) {
      anObject = {name: b};
    }
    return anObject;
  })();
}

Eager Initialization[edit]

Not a Singleton, but a constructor.

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

var o1 = new C(3);
var o2 = new C(4);
var o3 = new C(5);

Example: Constructors and prototype inheritance. jsbin

Singleton:

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

alert(anObject.name); 
alert(typeof b); // "undefined"

Function scope allows us to hide variable `b`. jsbin

Object literal notation does not provide any information hiding mechanism:

// exposed variables.
var a = 3;
var b = a + 2;
var anObject = {
  name : b;
};

Example: APE Animation Manager