JavaScript/Notes/Singleton: Difference between revisions

From Noisebridge
Jump to navigation Jump to search
Garrett (talk | contribs)
No edit summary
Garrett (talk | contribs)
Line 27: Line 27:
};
};


var anObject = new C(a);
var anObject = new C(3);
</source>
</source>
Example: Constructors and prototype inheritance.
Example: Constructors and prototype inheritance.

Revision as of 10:04, 23 November 2013

Singleton with information hiding.

Lazy Initialization

<source lang="javascript"> function getAnObject(a) {

 var anObject;
 var b = a + 1;
 return (getAnObject = function() {
   if(! anObject ) {
     anObject = {name: b};
   }
   return anObject;
 })();

} </source>

Eager Initialization

Not a Singleton, but a constructor. <source lang="javascript"> // Not a Singleton. var C = function(a) {

 var b = a + 2;
 this.name = b;

};

var anObject = new C(3); </source> Example: Constructors and prototype inheritance. jsbin

Singleton: <source lang="javascript"> var anObject = new function(a) { // hidden variables.

 var b = a + 2;
 this.name = b;

}(3);

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

The function scope allows us to hide variable `b`. jsbin

An object literal does not allow information hiding: <source lang="javascript"> // exposed variables. var a = 3; var b = a + 2; var anObject = {

 name : b;

}; </source>

Example: APE Animation Manager