JavaScript/Notes/Singleton: Difference between revisions

From Noisebridge
Jump to navigation Jump to search
No edit summary
Line 40: Line 40:
</source>
</source>
[http://jsbin.com/ErAHEFo/1/edit jsbin]
[http://jsbin.com/ErAHEFo/1/edit jsbin]
Example: [APE Animation Manager http://garretts.github.io/ape-javascript-library/build/anim/Animation.js]

Revision as of 09:25, 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(); </source> Example: Constructors and prototype inheritance. jsbin

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

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

}(3); </source> jsbin


Example: [APE Animation Manager http://garretts.github.io/ape-javascript-library/build/anim/Animation.js]